Reputation: 583
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
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