Programmatically navigate using react router V4
December 15, 2022 By sanxbot00To programmatically navigate using React Router v4, you can use the history
object. The history
object provides methods for navigating, such as push
and replace
.
Here is an example of how you can use the history
object to navigate to a new route:
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
function handleClick() {
history.push('/new-route');
}
return (
<button onClick={handleClick}>
Click to navigate
</button>
);
}
In this example, when the user clicks the button, the handleClick
function is called, which uses the history.push
method to navigate to the /new-route
route.
Alternatively, you can use the withRouter
higher-order component from react-router-dom
to inject the history
object into your component. This allows you to access the history
object without using the useHistory
hook.
Here is an example of how you can use the withRouter
higher-order component to programmatically navigate:
import { withRouter } from 'react-router-dom';
function MyComponent(props) {
function handleClick() {
props.history.push('/new-route');
}
return (
<button onClick={handleClick}>
Click to navigate
</button>
);
}
export default withRouter(MyComponent);
In this example, when the user clicks the button, the handleClick
function is called, which uses the history.push
method from the injected history
object to navigate to the /new-route
route.