Introduction
We have a page, for example a Form. And, upon submission we would want user to be redirected to some other page and pass some state or props so that that page can show some message or so.
Next.js Router - Pass State
- First import
withRouter
import { withRouter } from 'next/router'- Wrap your component export with
withRouter
export default withRouter(EditUser);Now in your component’s props, you have a router object.
Redirect to other Page and Pass State
I have a user edit form, and upon submission. I want user to be redirected to /user/<id>
And, I want to show a message that edit has been successful.
this.props.router.push({
pathname: `/users/${user.id}`,
query: {success: true}
});Here, I’m passing a query parameter to that page. So it will be:
/users/1234?success=trueRetrieve Value in Redirected Page
In my component jsx file, I want to show a bootstrap alert.
return (
<SimpleLayout>
{props.router.query.success &&
<div className="alert alert-success alert-dismissible fade show" role="alert">
Success.
<Button type="button" className="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</Button>
</div>
}
...
...
</SimpleLayout>
}
)Note the props.router.query.success













