'Router.push() working differently at different times
I want to use router.push() to change the url when clicking Search button. However, as far as I have noticed, this function works sometimes and sometimes not. In the final version, after pressing the button, the user should be redirected to the /search page with the text entered in the input field. However, this is not happening and I cannot find any error in my code.
That's my search function in index.js:
const [searchInput, setSearchInput] = useState("");
const router = useRouter()
const Search = () => {
router.push({
pathname: "/search",
query: {
city: searchInput,
}
},
);
};
And that's my form in index.js
<form className={"flex flex-col items-center mt-44 flex-grow"}>
<h1 className={"flex justify-center font-bold pt-20 text-4xl"}>Enter address</h1>
<div className={"flex w-full mt-5 hover:shadow-lg focus-within:shadow-lg max-w-md rounded-full border border-gray-200 px-5 py-3 items-center sm:max-w-xl lg:max-w-2xl"}>
<input
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
type={"text"} className={"flex-grow focus:outline-none"}/>
<SearchIcon className={"h-5 text-gray-500"}/>
</div>
<div className={"flex flex-col w-1/2 space-y-2 justify-center mt-8 sm:space-y-0 sm:flex-row sm:space-x-4"}>
<button
onClick={Search}
className={"btn"}>Search</button>
</div>
</form>
Maybe that's something with my WebStorm configuration as it works sometimes and sometimes not. I don't have any idea to be honest.
Solution 1:[1]
It is likely that the default form-submission is interfering with your Search function.
You probably want something like:
const Search = (e) => {
e.preventDefault();
router.push({
pathname: "/search",
query: {
city: searchInput,
}
},
);
};
See here for more info: https://www.robinwieruch.de/react-preventdefault/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Luke Storry |
