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?
-
See also: stackoverflow.com/questions/43862600/…Emilio Miralles– Emilio Miralles2023-05-22 22:49:57 +00:00Commented 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.Arjun Nayak– Arjun Nayak2024-10-31 10:59:33 +00:00Commented Oct 31, 2024 at 10:59
Add a comment
|
2 Answers
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.
Comments
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);