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 (
);
};
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.
Related Articles
The post How to programmatically navigate using React Router and JavaScript? appeared first on The Web Dev.