Next.js: Router.push with state
In next.js
you can pass query parameters like this
Router.push({
pathname: '/about',
query: { name: 'Someone' }
})
and then in your next page (here in /about
page), retrieve the query
via the router
props, which needs to be injected to Component
by using withRouter
.
import { withRouter } from 'next/router'
class About extends React.Component {
// your Component implementation
// retrieve them like this
// this.props.router.query.name
}
export default withRouter(About)
If you want your url remain clean, make a small addition to Prithwee Das's answer like below.
Router.push({
pathname: '/about',
query: { name: 'Someone' }
}, '/about');
Now you can access props in your component using props
...
const YourComponent = (props) => {
useEffect(() => {
console.log(props.router.query.name);
}, [props.router.query]);
return (
<React.Fragment>
...
</React.Fragment>
);
};
...
If you want 'clean' urls, one way to go about it is to add onClick handler to your link and store required information in context/redux store. It easy to implement if you already have one.
<Link href='...'>
<a onClick={()=>{dispatch(....)}}>Link<a/>
<Link>