Hamza Hameed
Hamza Hameed

Reputation: 583

how to redirect to partical page using history object in react-router-dom v6

I am using "react-router-dom" v6. When i try to redirect to another page using history object i got the following ERROR:

Cannot read properties of undefined (reading 'push')

Here is my code:

const Search = ({ history }) => {
  const [keyword, setKeyword] = useState("");

  const searchSubmitHandler = (e) => {
    e.preventDefault();
    if (keyword.trim()) {
      history.push(`/products/${keyword}`);
    } else {
      history.push("/products");
    }
  };
}

function App() {
  return (
    <Router>
      <div className="App">
        <Routes>
          <Route exact path="/" element={<Home />} />
          <Route exact path="/product/:id" element={<ProductDetails />} />
          <Route exact path="/products" element={<Products />} />

          <Route exact path="/search" element={<Search />} />
        </Routes>
        <Footer />
      </div>
    </Router>
  );

}

Upvotes: 1

Views: 709

Answers (1)

Drew Reese
Drew Reese

Reputation: 202836

The history object was replaced by a navigate function in react-router-dom version 6, accessed via the useNavigate hook.

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

const Search = () => {
  const navigate = useNavigate();
  const [keyword, setKeyword] = useState("");

  const searchSubmitHandler = (e) => {
    e.preventDefault();
    navigate(keyword.trim() ? `/products/${keyword}` : "/products");
  };
};

Upvotes: 1

Related Questions