I’m using React with the latest react-router-dom (version 5 or later).
After making a POST request via Axios, I want to redirect the user to another route (like /).
In older react-router versions, I used <Redirect />
directly inside the .then() callback, but now nothing happens.
How do I properly trigger navigation/redirect after a successful POST with the updated React Router?
I used to rely on the <Redirect />
component, but with react-router-dom v5+
, the recommended way is to use the useHistory hook. After your Axios POST completes successfully, call history.push(‘/’) to navigate programmatically.
Here’s a quick snippet:
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
const handleSubmit = () => {
axios.post('/api/data', payload).then(() => {
history.push('/');
});
};
return <button onClick={handleSubmit}>Submit</button>;
}
This works reliably and keeps the navigation logic inside your component.
In my projects, after switching to react-router-dom v5 or later, I moved away from conditionally rendering <Redirect>
.
Instead, I grab the history object with useHistory() and then call history.replace(‘/target-route’) or history.push(‘/target-route’) after the POST request finishes.
This lets you control the browser history precisely and avoids rendering complications.
Using push adds a new entry, replace swaps the current one. That’s how I handle redirects after POST in react-router-dom v5.
I totally agree with the point shared by @prynka.chatterjee and @tim-khorev
When I upgraded to react-router-dom v5+, I realized inside async callbacks doesn’t trigger navigation as expected. The cleanest way is to use the useHistory hook from react-router-dom.
After your POST completes, just call history.push(‘/desired-path’) to redirect. This approach aligns with the latest React Router best practices and helps keep your UI and navigation in sync. It’s also easier to test programmatically!