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?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

I figured it out.

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

and access state by:

  this.props.location.state.email

Solution 2

What i have done to pass data without context object is by using history prop,

this.props.history.push({
             pathname:"/shopdetail",
             state:{
                 key:"value"
              }
            });

And in the ShopDetail component you can access the object like,

this.props.location.state.key

Solution 3

if you don’t want to lose state upon a page refresh you can use local storage:

handleSubmit() {
  localStorage.setItem('email',
  JSON.stringify(this.state.email));
               }

and then retrieve from local storage on any other page, perhaps in componentWillMount:

componentWillMount(){
  let email = '';
  if (localStorage && localStorage.getItem('email')) {
     email = JSON.parse(localStorage.getItem('email'));
    }
   this.setState({email: email})
}

Solution 4

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>()

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply