I use React VITE v6.0.2 and I try to send a state via <Link>
component but the target page receives the state as empty.
The state is provide as follows
<Link to={{ pathname: `/post/${post.id}`, state: {'test': 'test'}, }} >{post.title || 'untitled'}</Link>
On the Post.jsx
, I receive the state this way:
import { useLocation } from 'react-router-dom'; function Post() { const location = useLocation(); console.log(location); ...
The problem is the state is the console.log
reports state as null
.
Object { pathname: "/post/134", search: "", hash: "", state: null, key: "sv8sy9m8" }
How to fix this promblem?
You need to place state as a separate property to the component like this:
<Link to={`/post/${post.id}`} state={{'test': 'test'}} >{post.title || 'untitled'}</Link>
Please note that for state value which starts with {{
, the outer curly braces is for saying it is a JSX
code and the inner {
is to define a javascript object.