Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass state/props when redirecting to another route in React?

I have a signup form and after a user signs up, it will redirect to the email confirmation page(/confirmation) where a user types a confirmation code that I sent via an email. When a user submits a confirmation code, I want to send the code and a user's email to server-side.

My signup form code(simplified):

    constructor(props){
          super(props);
          this.state = {
             email: '',
             password: '',
             errors: {},
          }
       }
    handleSubmit(e){
        e.preventDefault();
        this.props.userSignup(this.state).then(
            () => {
               this.context.router.push({
                  pathname: '/confirmation'
               })
            },

         )
   }
   render(){ ...

I do not want to add any params to my path.
How can I pass this.state.email to confirmation page?

like image 582
kay Avatar asked Oct 04 '16 08:10

kay


People also ask

How do you pass a state from one route to another in react?

With react-router, you pass state or data from one component to another component to use the react-router Link component. Data pass more quickly in the new version of react-router (v6). For example, you can pass an object's data into one component to another component.

How do you pass additional data while redirecting to a route 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.

Can you pass Props to react router link?

To recap, if you need to pass data from Link through to the new component that's being rendered, pass Link s a state prop with the data you want to pass through. Then, to access the Link s state property from the component that's being rendered, use the useLocation Hook to get access to location.


2 Answers

2021

You can also redirect by this component from react-router:

...
if (shouldRedirect) {
     return <Redirect to={"/some-path"} state={{ value: "hey"}}>
}
return <div>Welcome</div>

Then use it in the new component:

...
const location = useLocation()
const value = location.state.value

If you are using typescript, add types to the state as such:

interface State {
    value: string
}
const location = useLocation<State>()
like image 98
Gabriel Petersson Avatar answered Oct 14 '22 15:10

Gabriel Petersson


I figured it out.

 this.context.router.push({
     pathname: '/confirmation',
     state: {email: this.state.email}  
 })

and access state by:

  this.props.location.state.email
like image 40
kay Avatar answered Oct 14 '22 14:10

kay