score:2

Accepted answer

Sending Data with Route transition

You can send state along with the route transition using a Link's to object.

to: object

An object that can have any of the following properties:

  • pathname: A string representing the path to link to.
  • search: A string representation of query parameters.
  • hash: A hash to put in the URL, e.g. #a-hash.
  • state: State to persist to the location. <-- you need this
array.map((each)=>(
  <Link
    to={{
      pathname: `details/${each.id}`,
      state: {
        // whatever you need to send with the route transition
      },
    }}
  >
    <Card props={each}/>
  </Link>
))

Receiving the Route State

You've a few options.

  1. Easiest and more common way now with using the useLocation React hook in functional components.

    const { state } = useLocation();
    
  2. Decorating a component with the withRouter Higher Order Component and inject route props.

    If your component is decorated with withRouter it will have the current route props injected as props.

     export default withRouter(EachComponent);
    

    Access state from the location prop.

     const { state } = this.props.location;
    
  3. Directly render by a Route component and receive the route props.

    If your component is rendered directly by a Route it will have the route props passed to it.

     <Route path="/details/:id" component={EachComponent} />
    

    Access state from the location prop.

     const { state } = this.props.location;
    

Note: Route state is transient, meaning it only exists during the transition from one route to the next. If you navigate directly to a receiving route it won't have the state because it didn't use the transition from the route providing the state.

score:2

You can pass data with Link using location state or search (or query params):

<Link
  to={{
    pathname: '/path/to/my/component',
    search: 'id=123&name=foo',
    state: { data: 111 },
  }}
>
  Click Me
</Link>

And to retrieve in the MyComponent (e.g.using hooks):

const location = useLocation()
const query = new URLSearchParams(location.search)

console.log(location.state)
console.log(query.get('id'))
console.log(query.get('name'))

PS: You can also make a custom hook - useQuery for query params.

But be aware that if you open path - /path/to/my/component directly in the browser by typing it manually, there will be no location state or query params.

And URLSearchParams is not supported in Internet Explorer, if you need to support IE as well, you can use some package like query-string.


Related Query

More Query from same tag