I have the following code. (Also available on CodeSandbox: https://codesandbox.io/s/dreamy-aj-sxs411?file=/src/index.js)
App.js
import { Route, Routes } from "react-router-dom";
import Test01 from "./Test01";
import Test02 from "./Test02";
function App() {
return (
<Routes>
<Route path="/" element={<Test01 />} />
<Route path="/test02" element={<Test02 />} />
</Routes>
);
}
export default App;
Test01.js
import React from "react";
import { Link } from "react-router-dom";
function Test01() {
const pathname = "/test02";
const docId = "12345";
return (
<div>
<Link to={{ pathname: pathname, state: { docId: docId } }}>
Go to target page with docId
</Link>
</div>
);
}
export default Test01;
Test02.js
import React from "react";
import { useLocation } from "react-router-dom";
function Test02() {
const location = useLocation();
const docId = location.state?.docId || "Default Doc ID";
return (
<div>
<h1>Target Page</h1>
<p>Doc ID: {docId}</p>
</div>
);
}
export default Test02;
If I run the react page, I can not get the correct docId, and it only shows the Default Doc ID. What is wrong here?