Home >Web Front-end >JS Tutorial >How to Efficiently Pass Data Between React Router Pages?
Problem:
Navigating from a list of items to a detail page, passing along the details of the selected item.
Solution:
There are three main options for passing data between pages using React Router:
Option 1: Pass Route State
Send the item ID in the route's state:
v6 (Declarative):
<Link to="/home/userDetails" state={{ infoId: info.id }}>...</Link>
v6 (Imperative):
import { useNavigate } from "react-router-dom"; const navigate = useNavigate(); navigate("/home/userDetails", { state: { infoId: info.id } });
v5 (Declarative):
<Link to={{ pathname: '/home/userDetails', state: { infoId: info.id } }}>...</Link>
v5 (Imperative):
import { useHistory } from "react-router-dom"; const history = useHistory(); history.push({ pathname: '/home/userDetails', state: { infoId: info.id } });
Receive the state in the destination component:
v6:
const { state: { infoId } = {} } = useLocation();
v5:
if (props.location && props.location.state && props.location.state.infoId) { // Access info ID }
Option 2: Pass Something in the URL Path
Include the item ID in the URL path:
<Link to={`/home/userDetails/${info.id}`}>...</Link>
Receive the parameter in the destination component:
v6:
const { infoId } = useParams();
v5:
const infoId = props.match.params.infoId;
Option 3: Pass Something in the URL Query String
Append the item ID to the URL query string:
v6 (Declarative):
<Link to={{ pathname: '/home/userDetails', search: `?infoId=${info.id}` }}>...</Link>
v6 (Imperative):
import { useNavigate } from "react-router-dom"; const navigate = useNavigate(); navigate({ pathname: '/home/userDetails', search: `?infoId=${info.id}` });
v5 (Declarative):
<Link to={{ pathname: '/home/userDetails', search: `?infoId=${info.id}` }}>...</Link>
v5 (Imperative):
import { useHistory } from "react-router-dom"; const history = useHistory(); history.push({ pathname: '/home/userDetails', search: `?infoId=${info.id}` });
Receive the query param in the destination component:
v6:
const [searchParams] = useSearchParams(); const infoId = searchParams.get("infoId");
v5:
if (props.location && props.location.search) { const searchParams = new URLSearchParams(props.location.search); const infoId = searchParams.get("infoId"); }
The above is the detailed content of How to Efficiently Pass Data Between React Router Pages?. For more information, please follow other related articles on the PHP Chinese website!