I had passed the parameter to other component through Link
{props.posts.map((post)=>{
return (<>
<tr >
<td>{post.title}</td>
<td class="pull-right" id="underline"><Link to={{pathname:"/details",state:{title:post.title}}} >Details</Link> </td>
</tr>
</>)
})}
But when I tried to extract value of title in my Details component it showed error.
My Details.js is as
import React from 'react'
import { useLocation } from 'react-router-dom';
export default function Details(props) {
return (
<div>
<section class="section">
<br />
<section class="details">
<h4>Title:{props.location.state.title} </h4>
<br />
<h4>Categories: </h4><br />
<h4>Content: </h4>
</section>
<br />
</section>
</div>
)
}
I got the error as
TypeError: Cannot read properties of undefined (reading 'state')
You are trying to access the data from props, whereas you've passed data from the Link component, and not directly to the to-be-rendered component, to resolve this issue, you could make use of the useRouter hook.
Firstly create an instance of this hook. Use the created instance to drill through the state object.
If you're using react-router-dom v6 and above, there are few syntactical updates made. path and state needs to be passed as separate props and the state properties need to be wrapped within {}.
{props.posts.map((post)=>{
return (<>
<tr >
<td>{post.title}</td>
<td class="pull-right" id="underline"><Link to={"/details"} state={{title:post.title}}>Details</Link> </td>
</tr>
</>)
})}
MyDetails.js
import React from 'react'
import { useLocation } from 'react-router-dom';
export default function Details(props) {
const location = useLocation() //Instance of useLocation hook.
return (
<div>
<section class="section">
<br />
<section class="details">
<h4>Title:{location.state.title} </h4>
<br />
<h4>Categories: </h4><br />
<h4>Content: </h4>
</section>
<br />
</section>
</div>
)
}