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?
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.
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.
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.
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>()
I figured it out.
this.context.router.push({
pathname: '/confirmation',
state: {email: this.state.email}
})
and access state by:
this.props.location.state.email
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With