To programmatically navigate using React Router and JavaScript, we can use the useHistory
hook.
For instance, we write
import { useHistory } from "react-router-dom";
const HomeButton = () => {
const history = useHistory();
const handleClick = () => {
history.push("/home");
};
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
};
to call the useHistory
hook to return the history
object.
Then we define the handleClick
function that calls history.push
to navigate to the /home page.
And then we set the onClick
prop toi handleClick
to call handleClick
when we click oin the button.