Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

redux-router-kit

Package Overview
Dependencies
Maintainers
1
Versions
63
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

redux-router-kit

Routing tools for Redux/React

  • 0.0.39
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
390
increased by32.2%
Maintainers
1
Weekly downloads
 
Created
Source

Redux Router Kit

travis

Redux Router Kit is a routing solution for React that leverages Redux to store routing and transition states and enable powerful middleware and connect-powered components.

Features

  • Routing state lives in the store just like any other state.
  • Redux middleware has full access to routing and transition state along with your other store state.
  • The built-in onLeave/onEnter hooks have access to store state and dispatch. onLeave/onEnter hooks can easily see the current and next routing state.
  • Use connect to grab routing state anywhere in your component tree, just like other Redux store state.
  • Because transition states live in the store, you can render transition states or otherwise react to transition states in your React components.
  • Fetching routes asynchronously also exposes state in the store.
  • Even though routes can be fetched asynchronously, you can still easily work with the currently available routes synchronously.
  • Fall-through to server rendering for unmatched routes.
  • Ability to force server-rendering when needed.

Why not React Router?

If the features above aren't useful, by all means, use React Router instead! It's battle-tested, and Redux Router Kit borrows its concepts heavily! Redux Router Kit is an alternative that gives tighter integration with Redux.

Install

npm install redux-router-kit --save

Basic usage

import ReactDOM from 'react-dom';
import { combineReducers, applyMiddleware, Provider } from 'react-redux';
import {
  routerReducer, createRouterMiddleware, RouterContainer
} from 'redux-router-kit';

const HomePage = () => (
  <div>Home!</div>
);

const TodoApp = ({params}) => (
  params.id ? (
    <div>Todo: {params.id}</div>
  ) : (
    <div>Todos: {/* list todos */}</div>
  )
);

// You can point route paths directly to components in simple cases.
const routes = {
  '/': HomePage,
  '/todos': TodoApp,
  '/todos/:id': TodoApp
};

const reducer = combineReducers({
  router: routerReducer
});

const store = createStore(
  reducer,
  applyMiddleware(
    createRouterMiddleware({routes})
  )
);

const Root = React.createClass({
  render() {
    return (
      <RouterContainer routes={routes}/>
    )
  }
})

ReactDOM.render(
  <Provider>
    <Root/>
  </Provider>
  document.getElementById('app')
);

Nested routes

const Layout = ({children}) => (
  <div>
    <header>The Header</header>
    <div>{children}</div>
  </div>
);

const HomePage = () => (
  <div>Home!</div>
);

const TodoApp = ({children}) => (
  <div>{children}</div>
);

const TodoList = () => (
  <div>Todos: {/* list todos */}</div>
);

const TodoItem = ({params}) => (
  <div>Todo: {params.id}</div>
);

const routes = {
  '/': {
    component: Layout,
    routes: {
      // This is the "index" route. (Like a current directory.)
      '.': {
        component: HomePage
      },
      '/todos': {
        component: TodoApp,
        routes: {
          '.': {
            component: TodoList
          },
          ':id': {
            component: TodoItem
          }
        }
      }
    }
  }
};

RouterContainer / Router

The RouterContainer listens to routing state changes and delegates its props to the Router component, which takes the following props.

routes

Route mapping object. See the examples above.

router: PropTypes.object.isRequired,
routes: PropTypes.object.isRequired,

render: PropTypes.func,
renderBeforeCurrent: PropTypes.func,
renderNotFound: PropTypes.func,
renderDefault: PropTypes.func,
renderRoot: PropTypes.func,
renderComponent: PropTypes.func,
renderRoutes: PropTypes.func

renderBeforeCurrent({router})

If there is no current route, this function will be called.

render{router, query, params, matchedRoutes}

If you'd like to take control of all rendering for routes, pass in this function. No other rendering functions will be called. If no routes match, then matchedRoutes will be null.

renderRoutes({router, query, params, matchedRoutes})

Like render, but only called if there are matchedRoutes.

renderDefault({router, query, params, matchedRoutes})

If the matching routes don't have any components or don't reduce to a single element, this function will be called.

renderRoot({router, query, params, matchedRoutes})

After all components have reduced to a single element (or map of named elements), this function will be called to render any wrapping elements.

createElement({router, query, params, matchedRoutes, route, children})

For each component in a route, this function is called to return an element to be rendered. If child routes provide named components, named elements will be passed as props instead of children.

Routing component props

Components rendered by routes receive the following props. These will also be passed to createElement if you provide that function to RouterContainer.

router

This is the current routing state. An example of the routing state is:

{
  // When the url changes, `current` moves to `previous`.
  previous: {
    url: '/todos/123',
    // ... same properties as current
  },
  current: {
    url: '/todos/123?edit=true',
    query: {
      edit: 'true'
    },
    params: {
      id: 123
    },
    routeKey: ['/todos', ':id'],
    location: {
      host: 'www.example.com',
      pathname: '/todos/123',
      protocol: 'https:',
      // etc., just like browser's location
    },
    replace: false,
    state: null
  },
  // When the url changes, `next` will first get the new value of `current`.
  // Middleware or components can then cancel or redirect. If not canceled
  // or redirected, `current` will then become `next`. If `next` is null,
  // there is no current transition.
  next: null
}

matchedRoutes

An array of matched routes.

route

The specific route being rendered.

params

The route parameters.

query

The query parameters.

When you use RouterContainer, it responds to click/touch events so routing actions are automatically triggered. So you don't have to use a special <Link> component. A normal <a> will work just fine.

Routing action creators

routeTo(url, {event, replace, exit})

Dispatches a ROUTE_TO_NEXT action, which adds url to router.next state. Calls onLeave hooks for any routes which are removed and onEnter hooks for any routes which are added.

The route can be canceled with cancelRoute or redirected or exited with another routeTo.

If event is provided, it will be inspected for things like command-click to open new tabs.

If exit is provided, the route will roughly be equivalent to:

window.location.href = url

(Currently, only absolute urls are supported though.)

cancelRoute()

Cancels the router.next route and removes it from state.

Dispatching routing actions from components

If you do want to manually trigger routing actions, you can either manually wire up the action with connect:

import { routeTo } from 'redux-router-kit';

const AddTodoButton = ({routeTo}) => (
  <button onClick={() => routeTo('/todos/new')}>Add New Todo</button>
);

const ConnectedAddTodoButton = connect(
  null,
  (dispatch) => {
    routeTo(..args) {
      dispatch(routeTo(...args));
    }
  }
)(AddTodoButton);

Or you can use the included connectRouterActions to add the actions as props.

import { connectRouterActions } from 'redux-router-kit';

const AddTodoButton = ({routeTo}) => (
  <button onClick={() => routeTo('/todos/new')}>Add New Todo</button>
);

const ConnectedAddTodoButton = connectRouterActions(AddTodoButton);

Connecting your components to routing state

You can use connect to grab any routing state for your components. For example:

const TodoItem = ({query, todo}) => {
  const style = query.theme === 'dark' ? {
    color: 'white',
    backgroundColor: 'black'
  } : {};
  return <div style={style}>{todo.title}</div>;
};

const TodoItemContainer = connect(
  state => ({
    query: state.router.current.query
  })
)(TodoItem);

You can also use connectRouter to grab all routing state and action creators for your components. For example:

const TodoItem = ({router, todo}) => {
  const style = router.current.query.theme === 'dark' ? {
    color: 'white',
    backgroundColor: 'black'
  } : {};
  return <div style={style}>{todo.title}</div>;
};

const TodoItemContainer = connectRouter(TodoItem);

You should only use this if you want your component to be updated for all routing state changes. For example, the second example will update during routing transition, whereas the second will only update when the current route is changed.

Keywords

FAQs

Package last updated on 12 Apr 2016

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc