Home > front end >  UseNavigate is not working for dynamic search query
UseNavigate is not working for dynamic search query

Time:01-22

useNaviagte() of react-router-dom:^6.7.0 is not working for a dynamic search query. How to use my search text as a navigating route?

My Search component:


import { useNavigate } from 'react-router-dom';

function SearchBar() {
    const [searchItem, setSearchItem] = useState("")
    const navigate = useNavigate();

    const handleSubmit = (e) =>{
        e.prevnetDefault()
        navigate(`/search?q=${searchItem}`)
    };

  return (
    <div className='search-bar'>
        <form onSubmit={handleSubmit}>
            <label htmlFor='search'>Search: </label>
            <input
                type= "text"
                id= "search"
                onChange= {(e) => setSearchItem(e.target.value)}
            />
        </form> 
         ... ...    

In App.js:

{
    path: "/search",
    element: <div><Search/></div>,
  },

Package.json:

"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.7.0",

CodePudding user response:

it looks like there is a typo when you call e.preventDefault(). That may be causing an issue. Also, you could use controlled input by adding a value attribute to your input field like:

<input
  type= "text"
  id= "search"
  value={searchItem}
  onChange= {(e) => setSearchItem(e.target.value)} />

It would be helpful if you shared your search route page to share the code you are using there. You can use useSearchParams to grab the search parameters on your search page.

  • Related