Home > database >  passing parameter to another component using Link in react
passing parameter to another component using Link in react

Time:12-03

I know if I need to call another component then we need to pass like <A x={y}/> and we can access props.x inside A.

But here I need to call EditCertificate so I need to pass id to EditCertificate. but I am using Link here. I am not able to pass the id. when I am accesssing it, it is coming undefined.

<Link to={`/${props.certificate.id}/edit` }  >Edit</Link>

and I am calling this page like below.

<Route path ="/:id/edit" component={EditCertificate} ></Route>

how can I access :id inside the EditCertificate .when I am accessing it is giving undefined. do I need to pass some other properties.

CodePudding user response:

Since EditCertificate is rendered directly by the route:

<Route path ="/:id/edit" component={EditCertificate} />

the route props are passed to EditCertificate. You just need to access them from props.

const { id } = props.match.params;

if EditCertificate is a class component, then obviously access from this.props.

const { id } = this.props.match.params;

CodePudding user response:

since you're using react-router you can simply import useParams hook and get the id in you EditCertificate component

import { useParams } from 'react-router-dom'; 


const { id } = useParams(); // add inside your component body
  • Related