'Passing parameter without url to Component in Router
Is there any way to pass id in Router without mentioning in URL.
Like in following route, Its URL will have a id abc.com/abc/1
<Route exact path="/abc/:vid" component={AbcComponent} />
I want URL to be abc.com/abc and id should be available in AbcComponent. I tried following but I do not have ids in App.js to pass.
<Route exact path="/SpRides"
render={(props) => <SpRides vid={vid} spId={spId} depId={depId} {...props} />} />
Solution 1:[1]
Loved the answer given by @S0haib Nasir. Building on that, I used the following solution.
In the function component add the code below which would be triggered by the button click
props.history.push({pathname: '/abc', state: { id: 'some_value' }})In the destination component add the following
this.props.location.state.idto access the variableThen use
useEffectto save the variable in thelocalStorage. This addresses the issue to maintain the state as well in case something goes wrong. Addresses the flaw @S0haib Nasir mentioned as well about the refresh.
Solution 2:[2]
Here is a functional approach to solve it:
You can pass "state" prop ( it will push state in history) in React router Link and then access this in the targeted component using useLocation() hook.
<Link to='/abc/' state={{ id }}>
click here
</Link>
Now in App.js :
<Route exact path="/abc" component={AbcComponent} />
and then in AbcComponent file:
import { useLocation} from 'react-router-dom';
const AbcComponent= () => {
const location = useLocation();
console.log({location });
return <div> the id is : {location.state.id }</div>;
export default AbcComponent;
BONUS:
You can also add as usual Query params and access this using useParams() . Just add a state prop in Link. And in AbcComponent , use both useParams() and useLocation() to get the param and state.
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 | IronmanX46 |
| Solution 2 | Tahid |
