logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Next.js 14: Handling Params and Search Params

author
Generated by
Nitish Kumar Singh

30/07/2024

Next.js

Sign in to read full article

Reading URL Parameters

Suppose you have a dynamic route defined in your Next.js application, such as /products/[id]. This route captures the product ID from the URL, which can then be accessed within your component. Let’s see how this works:

// app/products/[id]/page.js const ProductPage = async ({ params, searchParams }) => { const { id } = params; const productApproved = searchParams?.productApproved //true or false // Perform data fetching based on the ID const product = await fetchProductById(id); return ( <div> <h1>{product.name}</h1> <p>{product.description}</p> </div> ); }; export default ProductPage;

In this example, params is automatically provided to your component when the route is matched. You can destructure the id directly from params and then use it to fetch the required data or render based on that specific product ID.

Utilizing Search Parameters

Search parameters are frequently used to filter, sort, or initialize the display of data. In Next.js 14, we can access these parameters efficiently using the useSearchParams hook in client components.

Here’s a practical example of how to implement useSearchParams:

// app/products/page.js 'use client'; import { useSearchParams } from 'next/navigation'; const ProductPage = () => { const searchParams = useSearchParams(); const category = searchParams.get('category') || 'all'; const sortBy = searchParams.get('sort') || 'default'; // Fetch products based on category and sort-by option const products = fetchProducts({ category, sortBy }); return ( <div> <h1>Products</h1> <ul> {products.map(product => ( <li key={product.id}>{product.name}</li> ))} </ul> </div> ); }; export default ProductPage;

In the ProductList component, we use the useSearchParams hook to retrieve the category and sort search parameters from the URL. Based on these parameters, we can fetch the necessary products, allowing us to provide a tailored view depending on user choices.

Combining Params and Search Params

One of the strengths of Next.js 14 is the seamless integration of both params and search params. You can design complex interfaces where routing and filtering work closely together.

// app/products/[id]/page.js 'use client'; import { useSearchParams } from 'next/navigation'; const ProductPage = async ({ params }) => { const { id } = params; const searchParams = useSearchParams(); const filter = searchParams.get('filter') || 'none'; // Fetch product details and apply filtering logic const product = await fetchProductById(id); // Example filtering logic, can vary based on requirement const filteredDetails = applyFilter(product.details, filter); return ( <div> <h1>{product.name}</h1> <p>{product.description}</p> <div> <h2>Details</h2> <pre>{JSON.stringify(filteredDetails, null, 2)}</pre> </div> </div> ); }; export default ProductPage;

In this example, we are fetching the product based on its ID from the dynamic route while also considering any filtering criteria provided through the search parameters. This showcases how the App Router in Next.js 14 allows for highly interactive and user-oriented applications.

With these tools, developers can create clean and efficient routing systems that efficiently handle both URL and query parameters, ensuring an optimal user experience. Next.js 14's improvements effectively address modern web demands, making it a vital framework in the developer’s toolkit.

Popular Tags

Next.jsApp RouterURL Params

Share now!

Like & Bookmark!

Related Collections

  • Mastering Next.js 14: App Router Deep Dive

    02/10/2024 | Next.js

  • Next.js 14 Performance Mastery

    08/09/2024 | Next.js

Related Articles

  • Server Actions

    02/10/2024 | Next.js

  • API Routes and Middleware Optimization in Next.js 14

    08/09/2024 | Next.js

  • Mastering Middleware in Next.js 14 App Router

    02/10/2024 | Next.js

  • Streaming and Suspense

    02/10/2024 | Next.js

  • Understanding Next.js 14

    08/09/2024 | Next.js

  • Next.js 14: Handling Params and Search Params

    30/07/2024 | Next.js

  • Understanding the App Router in Next.js 14

    30/07/2024 | Next.js

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design