Accessing params with react-router-redux

zoopz picture zoopz · Apr 24, 2017 · Viewed 10.9k times · Source

I'm using react-router-redux (https://github.com/ReactTraining/react-router/tree/master/packages/react-router-redux)

installed with

npm install --save react-router-redux@next

implemented like so:

<Route path='/resource/:id' component={Resource}/>

I'm trying to access the parameter for the id in the container, like so:

const mapStateToProps = (state, ownProps) => {
  console.log(ownProps)
  return {...state.resource, id: ownProps.params.id}
}

As shown in the react-router-redux docs.

I'm getting an error stating that ownProps.params is undefined however. So this works:

const mapStateToProps = (state, ownProps) => {
  return {...state.resource, id: ownProps.match.params.id}
}

When I log ownProps, however, I find that ownProps.match.params.id contains the id I require.

Is this a change in implementation or have I implemented the route wrong? Thanks

Answer

Kate Lizogubova picture Kate Lizogubova · Mar 22, 2018

I know that it's already closed question, but I think it would be helpful info for someone else

I'm using the same version and here is my solution for the task of getting params when you don't have access to match:

import { createMatchSelector } from 'react-router-redux';

const { params } = createMatchSelector({ path: '/resource/:id' })(state);

console.log(params.id); 

I'm using it in a redux-saga, not in the component. And for your situation, it would be better to use react-router props and get params from props.match.params.id