Passing values through React-Router v4 <Link />

Viewed 78141

Question: How can I pass a prop or a single value, like an _id, through React-Router's Link component, and catch it at the endpoint?

This is what I mean: Let's say we are on page /a. The Link will take the user to /b. As such <Link to='/b'>. Now, I need to pass an _id through the Link, from /a, to /b.

<Link to='/b' params={_id}>blah blah</Link>

The id I'm trying to pass is the property of an object in which the Link component is nested in.

I found this syntax params={} in another StackOverflow thread. My code compiled without breaking, so that probably means it worked? However, I'm not sure about how to retrieve this passed value at the endpoint.

Any help will be greatly appreciated.

4 Answers

If you want to send more than one parameter through a route, you can do it like this.

1.Link element

<Link to={`/exchangeClicked/${variable1} ,${variable2},${variable3}`} >Click
</Link>

2.Configure your route path to accept those parameters

<Route
      exact
      path="/exchangeClicked/:variable1,:variable2,:variable3"
      component={MyComponent}
 />

3.You can then access the param in the new route via,

<Typography variant="h4" color="inherit">
    Exchange:{this.props.match.params.variable1}
</Typography>


<Typography variant="Body 1" color="inherit">
    Type:{this.props.match.params.variable2}
</Typography>

<Typography variant="Body 1" color="inherit">
    Durabiliy:{this.props.match.params.variable3}
</Typography>

If you are using react hooks you can get the parameters passed from state object using useLocation

  1. Link to the other page

<Link to={{ pathname: `page/${id}`, state: { foo: 'bar'} }}>Click me</Link>

  1. Declare a route
<Route
  exact
  path={`page/:id`}
  component={BComponent}
/>
  1. Get the location parameters and then the use state containing your key-value pair object
const BComponent = (props) => {
  const location = useLocation();
  console.log(location.state.foo);

  return ()
}
Related