3
votes

Using redux and react router, I would like to access a route parameter on a component other than the one specified by the route.

I've got react-router, redux, and react-router-redux set up as follows and I would like to access the reportId parameter from my redux store.

const history = syncHistoryWithStore(browserHistory, store);

const store = createStore(reducers);

const routes = (
    <Router history={history}>
        <Route path="/" component={MainLayout} >
            <IndexRoute component={Home} />
            <Route path="reports">
                <Route path=":reportId" component={ReportViewerContainer}  />
            </Route>
        </Route>
    </Router>
);

ReactDOM.render(
    <Provider store={store}>{router}</Provider>,
    document.getElementById('root')
);

I've tried hooking up react-redux-router to store the route state, but I've found that there is nothing useful stored inside of redux besides the full path to the active route. This has left me with the options of either parsing out the reportId from the path in redux, or creating my own custom action in redux and updating it with the componentWillReceiveProps lifecycle method inside of my ReportViewerContainer component. There must be a better way?

3

3 Answers

4
votes

If you want to access the router parameter inside the component, the best way to achieve this by using withRouter

https://egghead.io/lessons/javascript-redux-using-withrouter-to-inject-the-params-into-connected-components

You will find the better understanding with above example.

2
votes

If you want to access the router in the redux store, there's a HOC called withRouter (docs). If I remember correctly, this will pass any router state to your component as props.

The only change you need to make to your component would be this:

import { withRouter } from 'react-router'

export default withRouter(ReportViewerContainer);
1
votes

So I think you can use context to fetch the location that will be passed through the Router. ( Refer that link on how it works.) This should give you a solid direction to work on.

This can also help you down the lane to work with internationalization as well.

class MyComponent extends React.Component {
    static contextTypes = {
        router: React.PropTypes.object
    };

    render(){
        // By declaring context type here, and childContextTypes
        // on the parent along with a function with how to get it,
        // React will traverse up and look for the `router` context.
        // It will then inject it into `this.context`, making it 
        // available here.
    }
}