Sometimes, we want to redirect page on click of a button with React Router v6.
In this article, we’ll look at how to redirect page on click of a button with React Router v6.
How to redirect page on click of a button with React Router v6?
To redirect page on click of a button with React Router v6, we use the useNavigate
hook.
For instance, we write
import React from "react";
import { useNavigate } from "react-router-dom";
function LoginLayout() {
let navigate = useNavigate();
const routeChange = () => {
let path = `newPath`;
navigate(path);
};
return (
<div className="app flex-row align-items-center">
<Container>
<Button color="primary" className="px-4" onClick={routeChange}>
Login
</Button>
</Container>
</div>
);
}
to call the useNavigate
hook to return the navigate
function.
Then we call navigate
with path
to navigate to the path in the routeChange
function.
Then we assign routeChange
as the value of the onClick
prop of the Button
to navigate to the path
on click.
Conclusion
To redirect page on click of a button with React Router v6, we use the useNavigate
hook.