Home > Net >  trying to pass Props from component to component inside a route but i get undefined Props
trying to pass Props from component to component inside a route but i get undefined Props

Time:04-09

this is the code of the first component that i'm send the props from it

const Devcard = ({dev}) => {
  return (
        <Link to={{pathname:`/dev/${dev._id}`, devProps:{dev:dev}}}>
        <Button variant="primary">Learn More</Button>
        </Link>
      </Card.Body>
    </Card>
  );
};


and this is the component that i'm getting in it the Props. i'm getting undefined Props in here

const DevProfile = (props) => {
    console.log(props.location.devProps.dev);
return (
<div></div>
)

plz check my code , thnx

CodePudding user response:

If you want to send props through Link Component in React Router, you must use the state prop in it. And at the navigated Component you access that value using location.state. And If you want to use template literals in your JSX(i.e., in <Link />) you must embed them with JSX Embedded Expression. In your case, your Solution is: <Link to={`/dev/${dev._id}`} state={{ dev: dev }}}. On Navigated Component, you access this using,

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

const DevProfile = () => {
   const location = useLocation();
   const { dev } = location.state;
   // Your Logic
}

CodePudding user response:

I'm assuming DevProfile component gets rendered on the button click. You can leverage react-router-dom's useLocation hook to access props passed via Link. Like this-

  import { useLocation } from 'react-router-dom'
    const DevProfile = () => {   
    const location = useLocation()   
    const { dev } = location.state    
    return (...) 
    }

Also, I'm not sure the syntax you used for Link is valid or not. But I'll share the syntax I mostly use-

<Link to={`/dev/${dev._id}`} state={{ dev: dev }}>
  • Related