tsepen
@tsepen
Frontend developer

Роутинг в NEXT js?

Как настроить NEXT js так чтобы при переходе по роуту /products/category - рендернился компонент-страница catalog.jsx ?

Пробовал на сервере добавить роуты, но это не помогло

server.get('/products/:slug', (req, res) => {
  return app.render(req, res, '/catalog', { slug: req.params.slug });
});
  • Вопрос задан
  • 1016 просмотров
Решения вопроса 1
@Aves
Можно сделать примерно так:

server.js
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}`);
  });
});

pages/catalog.js
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>
    );
  }
}

И переходить по
<Link href='/catalog' as='/products/some-category'>
  <a>Some category</a>
</Link>
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы