Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass props to the route when using react router <Link>

i'm trying to pass props to the route of the Link element. But when I open the invoiceDetails components, i says props is undefined.

Below is how I'm trying to pass the props. It is correctly setup because it goes to the InvoiceDetails component. I declared the routes in my index.js

<Link props={{name: 'jack', age: 25, city: 'Antwerp'}}to='/InvoiceDetails'><p>VIEW</p></Link>

And in the InvoiceDetails component

import React from 'react'
import DashboardHeader from '../dashboardHeader/dashboardHeader'
import { Link } from 'react-router-dom'
function InvoiceDetails(){
console.log(props)
    return(
        <div className='w-10/12 bg-gray-300 float-right min-h-screen'>
          <div className='w-10/12 fixed z-50'>
.........
)
}
export default invoiceDetails

I would like to pass the props to the invoicedetails component using variables that I get from a global redux state. For now the static data is fine, the same principles apply I guess.

like image 642
Jonas.D Avatar asked Dec 24 '19 12:12

Jonas.D


1 Answers

You can pass it by mentioning the props in state

<Link
  to={{
    pathname: "/InvoiceDetails",
    state: { name: 'jack', age: 25, city: 'Antwerp'}
  }}
/>

Read about it more here

And to use it in your next component you have to either wrap your component with a react-router-dom HOC withRouter or use useLocation hook they have provided.

EX- In your second component -

import {useLocation} from "react-router-dom";

function Child() {
 let data = useLocation();
 console.log(data); //state would be in data.state//
}
like image 108
Atin Singh Avatar answered Nov 14 '22 22:11

Atin Singh