Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js: Router.push with state

I'm using next.js for rebuilding an app for server side rendering. I have a button that handles a search request.

In the old app, the handler was this one:

search = (event) => {     event.preventDefault();     history.push({         pathname: '/results',         state: {             pattern: this.state.searchText,         }     }); } 

In the results class, I could get the state date with this.props.location.state.pattern.

So now I'm using next.js:

import Router, { withRouter } from 'next/router'  performSearch = (event) => {     event.preventDefault();     Router.push({ pathname: '/results', state: { pattern: this.state.searchText } }); }; 

In the results class, I use

static async getInitialProps({req}) {     return req.params; } 

I'm not sure if I have to add this to my server.js:

server.get('/results', (req, res) => {     return app.render(req, res, '/results', req.params) }) 

However, the function getInitialProps throws an error because req is undefined. Long text, short question: how to pass state or params to another page without using GET parameters?

like image 589
DaFunkyAlex Avatar asked Mar 15 '19 12:03

DaFunkyAlex


People also ask

How do you pass a state in next route in Javascript?

If you want to send "route state" you have to do it via query string, but you can actually "mask" the path that is shown in the browser via the as property. as - Optional decorator for the URL that will be shown in the browser. You can decorate the URL to match the path name.

How do you use a router to push?

To navigate to a different URL, use router. push . This method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL.

Can I use React router in Nextjs?

In React JS, we would install a package called react-router-dom to implement routing inside the application. But Next JS has its own inbuilt router from the next/link , with which we can navigate between the pages. Before using the next/link , we need to set up the different pages/routes inside the pages folder.


1 Answers

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) 
like image 118
Prithwee Das Avatar answered Sep 16 '22 19:09

Prithwee Das