Home > Software engineering >  How to get rid of ? in the URL when passing data via link component in next.js?
How to get rid of ? in the URL when passing data via link component in next.js?

Time:09-08

I am passing data via link component like this:

<div>
        {data.map((myData) => (
          <h2>
            <Link
            href={{
              pathname: `/${myData.title}`,
              query: {
                id: myData.id
              }
            }}>
            <a>{myData.title}</a>
            </Link>
          </h2>
        ))}
</div>

And getting this URL http://localhost:3000/this-is-a-title?id=630f3c32c1

Is there any other way to do the same but get rid of that ? and everything after it for better SEO?

CodePudding user response:

You could build your path like so:

<Link
  href={{
    // http://localhost:3000/this-is-a-title/630f3c32c1
    pathname: `/${myData.title}/${myData.id}`,
  }}>
  {myData.title}
</Link>

or any other format that works in your case e.g.

// http://localhost:3000/this-is-a-title:630f3c32c1
pathname: `/${myData.title}:${myData.id}`,

With React Router Dom you should be able to pick up the id using params

  • Related