skip to Main Content

When I want to search for a product and upon search button click it should be routed to the "/search?q=xxxx" page. I’m using React Nextjs 13 and my folder structure is like:

  • app –>
    • components –>
      • SearchBar.tsx
    • search –>
      • layout.tsx
      • page.tsx

Here is my SearchBar component code:

"use client";
import React, { useState } from "react";
import { TbSearch } from "react-icons/tb";
import { SearchBarProps } from "../../globals/types";
import { useRouter } from "next/navigation";

const SearchBar: React.FC<SearchBarProps> = (props) => {
  const [SearchQuery, setSearchQuery] = useState("");

  const router = useRouter();

  const handleSearch = (event: React.FormEvent) => {
    event.preventDefault();
    const encodedSearchQuery = encodeURI(SearchQuery);
    router.push(`/search?q=${encodedSearchQuery}`);
    console.log("current query ", encodedSearchQuery);
  };

  return (
    <form onSubmit={handleSearch} className="relative">
      <input
        value={SearchQuery}
        onChange={(e) => setSearchQuery(e.target.value)}
        placeholder={props.searchPlaceholder}
        type="text"
        className="bg-gray-100 border-0 rounded-full px-4 py-3 pl-5 w-full focus:outline-none"
      />
      <button type="submit">
        <TbSearch className="absolute right-5 top-1/2 transform -translate-y-1/2 text-xl text-primary font-bold hover:cursor-pointer" />
      </button>
    </form>
  );
};

On my page.tsx I am using some mock data. My problem is that I’m getting encodedSearchQuery in my console but after adding ?q= I can’t get the query in url parameter that would be something like ‘/search?q=abc’ and it remains as only ‘/search’.

How can I fix this?

2

Answers


  1. I assume giving query params as a combined string is filtered by the router. Hope this is better:

    router.push(pathname, { query: { param: 'value' } });
    

    You could join the multiple values as described in the createQueryString is shown below:

      const createQueryString = useCallback(
        (name: string, value: string) => {
          const params = new URLSearchParams(searchParams)
          params.set(name, value)
     
          return params.toString()
        },
        [searchParams]
      )
    
    router.push(pathname + '?' + createQueryString('q', 'param1'))
    

    On the destination page useSearchParams is the desired way to grab arguments.

    The full example is here.

    Login or Signup to reply.
  2. I checked it in Nextjs 14 and it works fine. Here’s a codesandbox. Perhaps you could try upgrading Nextjs version if that’s the problem.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search