close

[Solved] Router.push with state in Next.js

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn about Router.push with state in Next.js in javascript. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How To use Router.push with state in Next.js ?

  1. How To use Router.push with state in Next.js?

    To use Router.push with state in Next.js 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.

  2. Router.push with state in Next.js

    To use Router.push with state in Next.js 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.

Solution 1

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)

Solution 2

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>

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read

Leave a Comment