Passing values through React-Router v4

Passing props

You can pass arbitrary props to a route via the state object:

<Link to={{ pathname: '/route', state: { foo: 'bar'} }}>My route</Link>

Then you can access the state object from within your component:

const {foo} = props.location.state

console.log(foo) // "bar"

Passing parameters

Configure your route path to accept named parameters (:id):

<Route path="/route/:id" exact component={MyComponent} />

Then you can pass URL parameters such as IDs in your link to:

<Link to={`route/foo`}>My route</Link>

You can access the parameter within your component via the match object:

const {id} = props.match.params

console.log(id) // "foo"

Sources

Leave a Comment