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
- components –>
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
I assume giving query params as a combined string is filtered by the router. Hope this is better:
You could join the multiple values as described in the
createQueryString
is shown below:On the destination page
useSearchParams
is the desired way to grab arguments.The full example is here.
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.