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

Time:08-31

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?

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

CodePudding user response:

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

  • Related