Jane Doe
Jane Doe

Reputation: 187

React Links passing variables across pages

I have the following link setup on my /home page in react. Once the link is pressed I want to pass the variable stockRow to the /quotes page.

<Link to = "/quotes" params={{ testvalue: stockRow }} >

On my /quotes page I was wondering how to grab that variable?

export default function Quotes() {

let variable = //Grab stockRow

  return (

  ); 
}

Upvotes: 1

Views: 593

Answers (2)

gdh
gdh

Reputation: 13682

Updated the answer with more research:

Below are the different approaches to pass data using Link

1st approach:

  • pass the params as a query. In this case, it will appear as url in the query param.
<Link to={{pathname: `quotes`, search: `?testvalue=${stockRow}`}} />
  • receive it in the component like this:
const search = props.location.search;
const params = new URLSearchParams(search);
const testvalue = params.get('testvalue');
console.log(testvalue);
  • Note: also use query-string to parse the query
  • advantage of 1st approach is that you share the url with others and the data persists on refresh. You can also pass arrays/objects by serialising it

2nd approach:

  • use route param
  • configure your route like this
<Route path="/quote/:testvalue" component={Quotes} />
<Link to=`/quotes/${stockRow}`>Go To Quotes Page</Link>
  • receive it in the component like this:

export default function Quotes(props) {

let variable = props.match.params.testvalue

  return (

  ); 
}
  • advantage of 2nd approach is that you share the url with others and the data persists on page refresh. However you can only use minimal types of data structure like string and numbers.

3rd approach:

  • pass the data in the to prop of Link as a state value
<Link to={{
      pathname: '/quotes',
      state: { testvalue: stockRow }
    }}> My Link </Link>
  • receive it in the component like this:

export default function Quotes(props) {

let variable = props.location.state && props.location.state.testvalue

  return (

  ); 
}
  • advantage of this is that you can pass any kind of data to state. However on page refresh, data won't persist and you need to handle this case in your component.

Upvotes: 2

akhtarvahid
akhtarvahid

Reputation: 9769

You can access your passed value through router params

export default function Quotes({match}) {

 const { testvalue } = match.params;
 console.log(testvalue);

  return (

  ); 
}

Upvotes: 0

Related Questions