A
A
Andrey Okhotnikov2019-05-22 11:07:45
React
Andrey Okhotnikov, 2019-05-22 11:07:45

Routing in NEXT js?

How to set up NEXT js so that when navigating through the /products/category route, the catalog.jsx page component is rendered?
I tried to add routes on the server, but it did not help

server.get('/products/:slug', (req, res) => {
  return app.render(req, res, '/catalog', { slug: req.params.slug });
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aves, 2019-05-22
@tsepen

You can do something like this:

const {createServer} = require('http');
const next = require('next');

const port = parseInt(process.env.PORT, 10) || 4000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({dev});
const handle = app.getRequestHandler();

app.prepare().then(() => {
  createServer((req, res) => {
    const [, category] = req.url.split(/(?<=^\/products\/+)([^\/]+)/);
    if (!category)
      handle(req, res);
    else
      app.render(req, res, '/catalog');
  }).listen(port, err => {
    if (err)
      throw err;
    console.log(`> Ready on http://localhost:${port}`);
  });
});

import React from 'react';

export default class extends React.Component {
  static getInitialProps({asPath}) {
    const [, category] = asPath.split(/(?<=^\/products\/+)([^\/]+)/);
    return {category};
  }

  render() {
    return (
      <div>
        <h1>Catalog</h1>
        <p>{this.props.category}</p>
      </div>
    );
  }
}

And move on
<Link href='/catalog' as='/products/some-category'>
  <a>Some category</a>
</Link>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question