I need to pass the id to a different component.
import { Link } from "react-router-dom";
const Option = () => {
return (
<section className="section">
<Link
to={{
pathname: "/person",
state: { id: "12345" },
}}
>
<button class="button is-primary">Click Me</button>
</Link>
</section>
);
};
export default Option;
The component where I am accessing the id
const Person = (props) => {
let data = useLocation();
console.log(data);
return (
<section className="section has-text-centered mt-4">
<h1>Hello</h1>
</section>
);
};
export default Person;
But I am getting state as undefined. How do I access the id that I have passed in ?
You need to assign the passing props on route component assigned place not ah route navigation
Reference Example for passing props to router
Or else if you really do like passing props on onclick. use useHistory
hook then pass the state param
you could receive the state value via
props
in child component
Updated
you should pass the render params to the component like
<Route path="/person" render={Person} />
Is equal to
<Route path="/person" render={(params)=><Person {...params}/>} />
Then only you can receive the props value on child param
import { Link,useHistory } from "react-router-dom";
const Option = () => {
const history = useHistory();
function nav(){
history.push({
pathname: '/path',
state: { // location state
update: true,
},
});
}
return (
<section className="section">
<button class="button is-primary" onClick={nav}>Click Me</button>
</section>
);
};
export default Option;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments