0
0
NextJSframework~10 mins

URL state with searchParams in NextJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to get the current URL's search parameters using Next.js hooks.

NextJS
import { useSearchParams } from 'next/navigation';

export default function Page() {
  const searchParams = [1]();
  return <div>Search Params Loaded</div>;
}
Drag options to blanks, or click blank then click option'
AuseRouter
BuseState
CusePathname
DuseSearchParams
Attempts:
3 left
💡 Hint
Common Mistakes
Using useRouter instead of useSearchParams
Trying to access searchParams directly without a hook
2fill in blank
medium

Complete the code to read the value of the 'page' parameter from the URL search params.

NextJS
const page = searchParams.[1]('page');
Drag options to blanks, or click blank then click option'
Aget
BgetAll
Chas
Dset
Attempts:
3 left
💡 Hint
Common Mistakes
Using getAll which returns an array
Using set which modifies params instead of reading
3fill in blank
hard

Fix the error in the code to update the URL search params with a new 'filter' value.

NextJS
const searchParams = useSearchParams();
const newParams = new URLSearchParams(searchParams);
newParams.[1]('filter', 'active');
Drag options to blanks, or click blank then click option'
Aset
Bappend
Cget
Ddelete
Attempts:
3 left
💡 Hint
Common Mistakes
Using append which adds duplicate keys
Using get which only reads values
4fill in blank
hard

Fill both blanks to create a new URL with updated search params and navigate to it using Next.js router.

NextJS
import { useRouter } from 'next/navigation';

const router = useRouter();
const newParams = new URLSearchParams(searchParams);
newParams.set('sort', 'desc');
router.[1](`/products?$[2]`);
Drag options to blanks, or click blank then click option'
Apush
BnewParams.toString()
Creplace
DsearchParams.toString()
Attempts:
3 left
💡 Hint
Common Mistakes
Using replace instead of push when you want navigation history
Using searchParams.toString() which is the old params, not updated
5fill in blank
hard

Fill all three blanks to create a React component that reads 'category' from URL, updates it on button click, and navigates.

NextJS
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>;
}
Drag options to blanks, or click blank then click option'
Aget
Bset
Cpush
Dappend
Attempts:
3 left
💡 Hint
Common Mistakes
Using append instead of set to update category
Using replace instead of push for navigation