'How to pass id in path url as component property in react router v6 [duplicate]
I'm updating an outdated tutorial project using react hooks and react router v6. I want to pass the id in the path url to the component property..
function App() {
const findPalette = (id) => {
return colorsData.find((palette) => palette.id === id);
};
return (
<Routes>
<Route path="/" element={<h1>Palette List goes here!</h1>} />
<Route path="/palette/:id" element={<Palette palette={generatePalette(findPalette(requiredID))} />} />
</Routes>
);
}
What should I do in place of 'requiredID' to get it done?
Here is the code in the tutorial
<Route
exact
path='/palette/:id'
render={routeProps => <Palette palette={generatePalette(this.findPalette(routeProps.match.params.id))} />}
/>
I found useParams() in the documentation, but it is used inside the function component passed to the element property
function ProfilePage() {
// Get the userId param from the URL.
let { userId } = useParams();
// ...
}
function App() {
return (
<Routes>
<Route path="users">
<Route path=":userId" element={<ProfilePage />} />
<Route path="me" element={...} />
</Route>
</Routes>
);
}
Solution 1:[1]
Create a custom hook that wraps useParams:
const usePalette = () => {
const { userId: id } = useParams();
return useMemo(() => colorsData.find(palette => palette.id === id), []);
}
function ProfilePage() {
const palette = usePalette();
// ...
}
If you can't change ProfilePage create a wrapper component (ProfilePageWrapper) that uses the hook, and let it render ProfilePage.
const ProfilePageWrapper () => {
const palette = usePalette();
return <ProfilePage palette={palette} />;
}
Then use the wrapper in the route:
<Route path="/palette/:id" element={<ProfilePageWrapper />} />
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
