How to Use Dynamic Route Variable Inside React NextJS Component No Query String

This blog is reader-supported. When you make a purchase through links on my site I may make a small commission at no additional cost to you.

[SOLVED] How to use the dynamic route variable inside of a React/NextJS component without passing an additional query string.

Are you creating a website or single page app using NextJS? Do you want to pass data from an index or archive page to a single post or article page? Maybe you have a collection of items, like a portfolio, and need to link from the collection to the individual selection. This method allows you to leverage NextJS’s built-in dynamic routing to pass the dynamic route’s value onward from one React component to the next without having to append an ugly looking query string (?!).

This is one way – it worked for my use case of rendering a single post from a WordPress on to a NextJS dynamic route page named [slug].js inside of a ReactJS component.

export async function getServerSideProps(context) { 
  const res = await fetch("" + context.params.slug);
  const dataset = await res.json(); 

  return { props: { dataset } } 

Passing context to an asynchronous getServerSideProps() function is the trick. Inside the function is a standard API fetch. Returning the fetch result as an object wrapped in the props variable passes the dynamic route’s value back to the page’s controller.

Share this post!

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments