Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS - Pass props with Redirect component

How should you pass props with the Redirect component without having them exposed in the url?

Like this <Redirect to="/order?id=123 />"? I'm using react-router-dom.

like image 344
Michiel Avatar asked Aug 28 '18 18:08

Michiel


People also ask

How do I pass props through redirect?

To pass props to the Redirect component with React Router, we put it in the object we set as the value of the to prop. <Redirect to={{ pathname: "/order", state: { id: "123" }, }} />; to set the to prop to an object with the state property set to an object with the props.

Can we pass data in redirect in React?

Using Link So when we click on the Register link, it will redirect to the /register route. But Link also allows us to pass additional data while redirecting. Here, at the place of data_you_need_to_pass , we can pass a string or object , array and so on and in the /register route we will get that data in props.

How do I redirect a component in React?

The Redirect component was usually used in previous versions of the react-router-dom package to quickly do redirects by simply importing the component from react-router-dom and then making use of the component by providing the to prop, passing the page you desire to redirect to.


2 Answers

You can pass data with Redirect like this:

<Redirect to={{             pathname: '/order',             state: { id: '123' }         }} /> 

and this is how you can access it:

this.props.location.state.id 

The API docs explain how to pass state and other variables in Redirect / History prop.

Source: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md#to-object

like image 90
Sakhi Mansoor Avatar answered Sep 17 '22 13:09

Sakhi Mansoor


You should first pass the props in Route where you have define in your App.js

<Route path="/test/new" render={(props) => <NewTestComp {...props}/>}/> 

then in your first Component

<Redirect             to={{             pathname: "/test/new",             state: { property_id: property_id }           }}         /> 

and then in your Redirected NewTestComp you can use it where ever you want like this

componentDidMount(props){ console.log("property_id",this.props.location.state.property_id);} 
like image 22
Barat Kumar Avatar answered Sep 21 '22 13:09

Barat Kumar