2

I am wanting to statically generate various menu pages based on the 'category' and 'subcategory' query parameters of the URL, such as: '/menu?category=savory'. Since I only have a few expected categories and subcategories, I thought static generation would work very well with the menu page but I have not found any solutions to this. Would the only way to do this be to have the category and subcategory values as dynamic route segments instead of query parameters?

2
  • See also: stackoverflow.com/questions/43862600/… Commented May 22, 2023 at 22:49
  • I think you are referring to a problem no 1 seams to be understanding. You are asking if there is a way to cache data with prerendered pages duing build time, but your page takes search params. I want into same issue where my page needs search params for filtering and still want to have few routes have been cached. But I don't think that's possible because in next js searchParams are considered special. Commented Oct 31, 2024 at 10:59

2 Answers 2

0

You can use the next/router with conditional rendering in any component.

For ?category=savory:

import { useRouter } from 'next/router';

export default function MenuComponent() {
  const router = useRouter();

  return(
    <div>
      {router.query.category == "savory" ? ( <p>savory</p> ) : ( <p>other</p> )}
    </div>
  );
}

Note: it will be empty during pre-rendering, so you need to catch that with appropriate defaults.

Sign up to request clarification or add additional context in comments.

Comments

-1

Since you only want to read the url query parameters, useSearchParams is the hook for you.

const searchparams = useSearchParams();
const category = searchparams.get("category");

In Next.js 13 and above searchparams is removed from the useRouter hook. Instead useSearchParams is added and it is read only.

Although you can change it like this,

const params= new URLSeachparams(searchparams);
params.set("category", somthingelse);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.