In React, we can programmatically navigate using React Router by using the useHistory hook provided by React Router.
For instance we write
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
const handleClick = () => {
// navigate to a specific route
history.push('/other-route');
};
return (
<button onClick={handleClick}>Go to other route</button>
);
}
To use the useHistory hook to return the history object.
Then we call push to navigate to the /other-route route.
This is the most common method for programmatically navigating using React Router.