'Pass Dynamic variable as prop from slug
In my App.js file I have one reusable element on which I provide a value as props.
Currently the value is somehow manually, I would like React to pass it dinamically, to be taken from it's path i.e \a.
<Route path="/a" element={<General site="a" />}> </Route>
<Route path="/b" element={<General site="b" />}> </Route>
Instead of providing a static prop as a or b I want it to be taken from it's path var ==> /a to a and /b to b
So I was hoping of using something like this:
<Route path="/b" element={<General site={Route.path} />}> </Route>
Where {path} has to have the value without /.
Hope that it is clear what I am trying to achieve.
Later Edit. I tried with {Route.path}, but if you have 2 or more variables, react will pick the last one which is not ok. Seems like a bug. Whenever you click on /a it provides the path as \b which is not correct
<Route path="/a" element={<General site={Route.path} />}> </Route>
<Route path="/b" element={<General site={Route.path} />}> </Route>
Cheers!
Solution 1:[1]
You need to use dynamic path (I assume you are using react-router library):
<Route path='/:site' render={(props => <General site={props.match.params.site} />)} />
Solution 2:[2]
If you are using React Route V6, use the hooks useLocation and useParams.
https://reactrouter.com/docs/en/v6/api#uselocation
https://reactrouter.com/docs/en/v6/api#useparams
Suppose you were making an editor page and wanted to show same page for creating a new doc or editing an existing doc.
If paths are /new-doc or /docs/:docId
import {
useLocation,
useParams
} from "react-router-dom";
...
export default function MyPage(props) {
const location = useLocation();
const params = useParams();
const docId = location.pathname !== "/new-doc" && params.docId; //path param docId can be fetched as `params.docId`
...
}
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 | Marek ?ernĂ½ |
| Solution 2 |
