In react-router-dom version 6
useHistory() is replaced by useNavigate() ;
import {useNavigate} from 'react-router-dom';
const navigate = useNavigate();
navigate('/home')
// React Router v6
import { useNavigate } from 'react-router-dom';
export function GoHome() {
let navigate = useNavigate();
const handleClick = e => {
e.preventDefault();
navigate('/home');
}
return <button onClick={handleClick}>Go to Home</button>
}
For those who are struggling with route v6 and more. You must define a function outside of your component Class and use it as following:
function myParams(Component) {
return props => <Component navHook={useNavigate()} />;
}
in your Class component:
this.props.navHook('/SomeWhere')
And keep in mind you have wrap your Class in your function:
export default myParams(Card);
<Navigate to="/dashboard" replace={true} />
import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
const submitHandler = async (event) => {
event.preventDefault();
try {
await submitForm();
navigate("/success"); // Omit optional second argument
} catch (error) {
navigate("/error", { state: { message: "Failed to submit form" } }); // Pass optional second argument
}
};