How can I use one component (page) for multiple route in Next JS

Viewed 7445

As you all know Next JS doesn't have any route, I am trying to build a web app in next JS in which I have to use the same component for multiple routes without copy pasting in to different directory.

Directroy structure:

src
    pages
        new (AddListComponent)
        edit-[id] (AddListComponent)

AddListComponent

import React from 'react'
import { withRouter } from 'next/router'

class Listing extends React.Component {
    constructor(props){
        super(props)
        this.state = {
        }
    }
    render () {
        return (
            <div>This is my new component</div>
        )
    }
}
export default withRouter(Listing)
2 Answers

Inside the route directory you can import and export the component from another directory.

Inside your second route /myPage2/index.js :

import MyPage from ../myPage.js
export default MyPage

You can create a page with optional parameters.

pages
 ┣ tasks
 ┃ ┣ manage
 ┃ ┃ ┗ [[...id]].jsx
 ┃ ┣ index.jsx
 ┃ ┗ service.js
 ┣ _app.jsx
 ┣ dashboard.jsx
 ┣ index.jsx
 ┗ login.jsx

/tasks/manage and tasks/manage/14 will route the same component [[...id]].jsx

  • Do not forget to use double brackets and three dots. [[...foo]].jsx

Catch all routes can be made optional by including the parameter in double brackets ([[...slug]]).

For example, pages/post/[[...slug]].js will match /post, /post/a, /post/a/b, and so on.

Please check for more info.

Related