How to change and add query strings in the app folder of Next.js? – Next.js

by
Ali Hasan
next.js reactjs

The Problem:

How to modify and append query strings within the app folder in a Next.js application, specifically when working with Next.js version 13.4 or later?

The Solutions:

Solution 1: Using `router.push`

In the `app` directory, `router.push(href: string)` only takes a `href` parameter. To change the query parameters, you can use the `createQueryString` function to create a query string and append it to the `href`:

import { useRouter } from "next/navigation";

const createQueryString = (name, value) => {
  const params = new URLSearchParams();
  params.set(name, value);
  return params.toString();
};

const ExampleClientComponent = () => {
  const router = useRouter();

  return (
    <>
      <button
        onClick={() => {
          router.push("/posts?" + createQueryString("sort", "asc"));
        }}
      >
        ASC
      </button>
      <Link href={"/posts?" + createQueryString("sort", "desc")}>DESC</Link>
    </>
  );
};

Solution 2: Using `searchParams`

In the page component, you can access the query parameters using `searchParams`:

// app/posts/page.js
export default function Page({ searchParams }) {
  return <div>{searchParams.sort}</div>;
}

Solution 3: Using `useSearchParams`

You can also use the `useSearchParams` function to access and manipulate the query parameters:

import { useSearchParams } from "next/navigation";

export default function Page() {
  const searchParams = useSearchParams();
  return <div>{searchParams.get("sort")}</div>;
}

Solution 2: Using Query Strings

The createQueryString function was created to manipulate query strings:

export const createQueryString = (pathname, router, name: string, value: string) => {
   let searchParams = new URLSearchParams(window.location.search)
   if (value) {
      if (!Array.isArray(value)) {
         if (!searchParams.has(name)) searchParams.append(name, value)
         else searchParams.set(name, value)
      } else {
         if (!searchParams.has(name)) searchParams.append(name, value.join())
         else searchParams.set(name, value.join())
      }
   } else if (searchParams.has(name)) searchParams.delete(name)
   const newUrl = pathname + '?' + searchParams.toString()
   router.push(newUrl)
}

In the component, you can use this function like this:

import { createQueryString } from 'helpers'
import { usePathname, useRouter } from 'next/navigation'

const TablePagination = (: Props) => { const router = useRouter() const pathname = usePathname() return ( <Pagination count={50} rowsPerPage={10} page={pagination.page - 1} onPageChange={(event, page) => createQueryString(pathname, router, 'page', ${page + 1})} onRowsPerPageChange={(event) => createQueryString(pathname, router, 'take', event.target.value) } /> ) }

Q&A

How to push new query parameters and update the existing ones from the app directory of Next.js?

router.push from next/navigation in the app directory accepts only the href as a string. Therefore, you need to create your own query string.

Can you provide a code snippet on how to create a query string in the app directory?

You can use the createQueryString function to create a query string. This function takes three parameters: the pathname, the router, and the name and value of the query parameter you want to set or update.

How to use the createQueryString function in a client component?

To use the createQueryString function in a client component, you can import the useRouter hook from next/navigation and call the createQueryString function with the pathname, the router, and the name and value of the query parameter you want to set or update. The createQueryString function will then update the URL with the new query parameters.

Video Explanation:

The following video, titled "Build a Search Bar with Next.js and Prisma (Search API endpoint ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

... Next.js application using Prisma. We'll look at how to add search query params to the URL, and use the search params to make a GET request ...