29

Using the newer version of React Router, how do you pass parameters to the route you are transitioning to if you are transitioning using the browserHistory.push()? I am open to using some other way to transitioning if browserHistory does not allow this. I see that in my top most child component in React Router there is this.props.routeParams but I can't seem to get this populated with values I want from the previous route when transitioning.

jiminssy
  • 2,149
  • 6
  • 28
  • 45

3 Answers3

65

Now you will have do something like this

history.push({
  pathname: '/about',
  search: '?the=search',
  state: { some: 'state' }
})

Here is the link for API documentation

Serge Kishiko
  • 466
  • 1
  • 6
  • 13
Deadfish
  • 2,047
  • 16
  • 17
3

for react router v4 we can do things this way:

const history = useHistory();
 history.push({
      pathname: "/create-opinion/"+user,
      state:{  username:userName}
    };

and to get it from the other component simply:

const history = useHistory();

then to get username:

const username = history.location.state.username;

don't forget to import useHistory from react-router-dom

if you haven't install react-router-dom yet type:

$ npm install --save react-router-dom
user8453321
  • 344
  • 1
  • 5
  • 12
0

If you want to pass a path parameter you can do it as follows. I am using sample component Merchant.

Define Route

<Route exact path="/merchant/:id" render={(props) => <Merchant id={props.match.params.id}/>} />

Define History

const history = createBrowserHistory({
    basename:''
})

Add to history with parameter

history.push(`/merchant/${id}`)
Ruchira Nawarathna
  • 1,137
  • 17
  • 30