App.js where all my Routes are declared:
function App() {
return (
<div className="App">
<Routes>
<Route path="/">
<Route index element={<Homepage />} />
<Route path="settings" element={<Settings />} />
<Route path="report/:runId" element={<TestReport />} />
<Route path="report/:runId/:specFileName" element={<SpecFile />} />
</Route>
</Routes>
</div>
)
}
Here I have the Link to (in my current case) /report/2/Login where I want to pass some parameters:
<TableCell>
<Link
to={`/report/${this.props.runId}/${specFile.name}`}
state={{ testcases: this.props.testcases }}
>
{specFile.name}
</Link>
</TableCell>
Here I want to access my parameters:
import { useLocation } from "react-router-dom";
export default function SpecFile() {
const location = useLocation();
const { from } = location.specFile.name;
console.log(from); // Should print "Login" instead gives Error Message: Cannot read properties of undefined (reading 'name')
}
location.specFile.name; is invalid and breaks because the location object doesn't have any specFile property.
interface Location { pathname: string; search: string; hash: string; state: unknown; key: string; }
Access the passed route state on location.state, specifically on location.state?.testcases.
For the given route <Route path="report/:runId/:specFileName" element={<SpecFile />} /> the SpecFile component should use the useParams hook to access the route path params runId and specFileName.
Example:
import { useLocation, useParams } from "react-router-dom";
export default function SpecFile() {
const { id, specFileName } = useParams();
const { state } = useLocation();
const { testcases } = state || {};
useEffect(() => {
console.log({ id, specFileName, testcases });
}, [id, specFileName, testcases]);
...
}
There is a hook in react-router-6 for this.
import { useSearchParams } from 'react-router-dom';
and then use it like:
const [searchParams] = useSearchParams();