Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide parameters from Route after accessing parameters in reactjs

Tags:

I have create basic React Application where i have created one component in this. When pattern matches component get loads.

<HashRouter>
    <Route path='/:id1/:id2' component={withRouter(component_name)}/></HashRouter>

When i run application Url looks : http://localhost:4000/#/1/2

Now in my Component i am able to read parameters by this.props.match.params.id1. After reading params from url i want to hide it from url should look like this. http://localhost:4000/#/

Could someone help me out this your valuable answers.

Thanks in advance.

like image 800
Sravan Shetty Avatar asked Feb 28 '19 12:02

Sravan Shetty


1 Answers

Instead of having to remove the params from the url you can pass the using the router state for example if you are redirecting with a link you can do something like

<Link to={{
  pathname: '/',
  state: { params: {id1: value1, id2: value2} }
}}> My Link </Link>

and then in your component that has been routed using the router you can get them like:

this.props.location.state.params.id1
this.props.location.state.params.id2

In this way you avoid the need of having to remove the path params from the url

Update

If you need the url to be matched in the browser you can have an intermediate route that extract the params and then redirect to the right component like:

<Route
   path="/test/:id1/:id2"
   component={({ match }) => {
     return <Redirect to={{ path: '/component-route', state: {...match.params}}} />;
   }}
 />

In this way the router will match the first url and then redirect to another component passing the pass params through the state. In that way you can access the state params like I mentioned above.

Hope it helps

like image 100
ocespedes Avatar answered Oct 19 '22 17:10

ocespedes