Home > Net >  Nextjs pass id but don't display in url
Nextjs pass id but don't display in url

Time:08-08

I want to pass product id from category to product page without displaying on url

Category.js

<h2>
  <Link href={{
      pathname: `/product/car/${title}`,
      query: {
          id: Item.id,
      },
  }} as={`/product/car/${(Item.description}`}>{Item.description}</Link>
</h2>

[...slug].js

function slug(context) {
    const Router = useRouter()
    const { slug } = Router.query;
    console.log(slug)
    console.log(context.params);
// want to get id here
    return (
        <div className="container">
            hello {slug}
        </div>
    )
}

export default slug;

Result:

What I trying to achieve is get id from category page link, if I do this /product/car/1/bmw I able to get id but I want this url /product/car/bmw but also get id, is there anyway?

CodePudding user response:

Can you try this way?

import { withRouter } from 'next/router'

const C = (props) => {
  useEffect(() => {
    console.log(props.router.query)
  }, [props.router])
}

export default withRouter(C);

CodePudding user response:

May this code works for you!

Import route like this:

import { useRouter } from 'next/router'

Define route like this:

const router = useRouter();

Change route like this:

    <button
      type="button"
      onClick={() => {
        router.push({
          pathname: `/product/car/${Item.description}`,
          query: { id: Item.id },
        })
      }}
    >
        {Item.description}
    </button>
  • Related