Home > Mobile >  How to pass an object through Link
How to pass an object through Link

Time:03-23

I need to pass an object through Link in react-router v6. How can I do it? I attached a fragment of my code. The user must come to another component

import React from 'react'
import { Link } from 'react-router-dom'
export default function UserCard(props) {

  const { name, company, city, user } = props
  return (
    <div className='user-card__container' >
      <div className='user-card__main-info'>
        <div className='user-card__fullname'> <span className='main-info__point'>ФИО:</span>     {name}</div>
    <div className='user-card__city'> <span className='main-info__point'>город: </span>{city}</div>
    <div className='user-card__company'> <span className='main-info__point'> компания: </span>{company}</div>
  </div>
  <Link to={`user/${user.id}`}
    className='user-card__button-profile'>
    <div >
      Подробнее
    </div>
  </Link>
</div>
)}

CodePudding user response:

I am not sure if with react-router v6 it's possible to pass an object as a query Params. You can use query-string package to parse queryParams into object which will allow you manipulate them easily and then stringify them before you pass them to link.

import qs from 'query-string';

...
const queryParam = qs.parse(location.search);
const newQueryParam = {
   ...queryParam,
   user_role: 'admin',
   something_else: 'something',
}


...
<Link to={{ pathname: '/admin/users', search: qs.stringify(newQueryParam)}} />

CodePudding user response:

somthing like this:

<Link to={{
          pathname: `user/${user.id}`,
          search: `objname=${JSON.stringify({ ...yourObj})}`         }
        } >

or

 <Link to={{
          pathname: `user/${user.id}`,
          query: {
              param1: param1, 
              param2: param2, 
              paramobj: JSON.stringify(yourObj)
              }
        } >
  • Related