Whenever a query is submitted in my search bar component, the current webpage doesn’t actually change, with only a /?
showing up at the end of the website’s URL. However, when I manually type in an incorrect page route into the router (for example, /test
), the search bar suddenly works as intended whenever I submit a query with it by pushing the query to the end of the URL path. Reloading the web page reintroduces the problem. For the component to be working correctly, it should be pushing /search?q=[QUERY HERE]
to the router.
What’s going on? Is this a bug with NextJS or am I doing something incorrectly? For context, I’m using the App Router and this component is a layout component.
search-bar.tsx:
"use client";
import { useState } from "react";
import styles from "../app/styles/navbar.module.css"
import { useRouter, useSearchParams } from "next/navigation";
const SearchBar: React.FC = () => {
const [query, setQuery] = useState("");
const searchParams = useSearchParams();
let router = useRouter();
return (
<form className={ styles.search } onSubmit={() => router.replace("/search?q=" + query)}>
<input type="text" placeholder="Search here..." value={ query } onChange={(e) => setQuery(e.target.value)}/>
<button type="submit" onClick={() => router.replace("/search?q=" + query)}>Search</button>
</form>
);
}
export default SearchBar;
2
Answers
Without knowing what your
/search
route does exactly I can not provide the best answer, but I think it could be the issue with replace and you could userouter.push
instead ofrouter.replace
to retain navigation history, so it can persist between reloads. Also, try usingLink
component that is provided byNextJS
. You can wrap theform
in Link component like this:I hope this helps you, at least that is how I would do it, and it worked previously for me.
Make sure you have the directory this way:
app/search/page.tsx
This is how the page component should be named
Page
I also factored your
searchBar
component as so: