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