Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the best way to query previous slug name in NextJS

How to get postID?

Hi I am making a simple post detail page with NextJS.
I have my url: [postID]/[title].tsx

And for the post detail page, I want to query for postID: green highlighted area, so that I can fetch the post’s data with it.

I use useRouter to get title name, so I am guessing I can do same thing to postID too.
How can I query for any slug key word like my case?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My code

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

export default function Title() {
    const router = useRouter()
    const title = router.query.title
    // const postID = router.query... I want to get postID from url somehow.
  return (
    <div>{title}</div>
  )
}

enter image description here

>Solution :

So you are thinking of passing n level of slug if I am not wrong.

Like this => http://localhost:3000/postDetail/postId/title/city/tags

Here in the URL above postDetail is your page and postId/title/city/tags are query params(slug)

Solution

  1. Create a folder inside the pages folder (pages/productDetail)
  2. And then create a file named [...slug].js inside pages/productDetail

[…slug].js

import { useRouter } from 'next/router';

export default function Slug() {
  const router = useRouter();
  console.log(router.query.slug); // you will get an array of all query params here.. check your console...
  return (
    <>
      Pass data like http://localhost:3000/postDetail/postId/title/city/tags
    </>
  );
}

Stackblitz Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading