In React Router, you can pass data to a new route using the Link component by utilizing the state property within the to prop. This method allows you to transmit information without embedding it directly into the URL.
Passing Data with Link:
import { Link } from 'react-router-dom';
<Link
to={{
pathname: '/target-route',
state: { key: 'value' },
}}
>
Navigate to Target
</Link>
In this example, the state object { key: 'value' } is passed to /target-route.
Accessing Passed Data in the Target Component:
import { useLocation } from 'react-router-dom';
const TargetComponent = () => {
const location = useLocation();
const { key } = location.state || {};
return (
<div>
<p>Received data: {key}</p>
</div>
);
};