Complete the code to get the current URL's search parameters using Next.js hooks.
import { useSearchParams } from 'next/navigation'; export default function Page() { const searchParams = [1](); return <div>Search Params Loaded</div>; }
The useSearchParams hook from Next.js lets you access the URL's query parameters easily.
Complete the code to read the value of the 'page' parameter from the URL search params.
const page = searchParams.[1]('page');
The get method retrieves the first value of a given search parameter key.
Fix the error in the code to update the URL search params with a new 'filter' value.
const searchParams = useSearchParams(); const newParams = new URLSearchParams(searchParams); newParams.[1]('filter', 'active');
The set method updates or adds a key-value pair in URLSearchParams.
Fill both blanks to create a new URL with updated search params and navigate to it using Next.js router.
import { useRouter } from 'next/navigation'; const router = useRouter(); const newParams = new URLSearchParams(searchParams); newParams.set('sort', 'desc'); router.[1](`/products?$[2]`);
Use router.push to navigate to a new URL. The toString() method converts URLSearchParams to a query string.
Fill all three blanks to create a React component that reads 'category' from URL, updates it on button click, and navigates.
import { useSearchParams, useRouter } from 'next/navigation'; import React from 'react'; export default function CategoryFilter() { const searchParams = useSearchParams(); const router = useRouter(); const category = searchParams.[1]('category') || 'all'; function updateCategory() { const newParams = new URLSearchParams(searchParams); newParams.[2]('category', 'books'); router.[3](`/shop?${newParams.toString()}`); } return <button onClick={updateCategory}>Show Books</button>; }
Use get to read the category, set to update it, and push to navigate to the new URL.