Last updated: Apr 7, 2024
Reading timeยท3 min

To redirect on form submit using React Router:
useNavigate() hook, e.g. const navigate = useNavigate();.navigate() function passing it the path - navigate('/contacts').navigate() function lets us navigate programmatically.import {Link, Routes, Route, useNavigate} from 'react-router-dom'; function Home() { const navigate = useNavigate(); const handleSubmit = event => { event.preventDefault(); // ๐๏ธ Redirect to /contacts navigate('/contacts'); }; return ( <form onSubmit={handleSubmit}> <input /> <button type="submit">Submit</button> </form> ); } export default function App() { return ( <div> <div> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/contacts">Contacts</Link> </li> </ul> </nav> <Routes> <Route path="/contacts" element={<Contacts />} /> <Route path="/" element={<Home />} /> </Routes> </div> </div> ); } function Contacts() { return <h2>Contacts</h2>; }

The useNavigate hook returns a function that lets us navigate programmatically, e.g. after a form is submitted or a button is clicked.
The navigate function can be passed a delta, e.g. -1 to go one page back,
1 to go one page forward or a path, e.g. navigate('/about').
The function also takes an options object.
const handleSubmit = event => { event.preventDefault(); // ๐๏ธ Redirect navigate('/contacts', {replace: true}); };
When the replace property is set to true on the options object, the
current entry in the history stack gets replaced with the new one.
This is useful, for example, when a user logs in - you don't want them to be able to click the back button and get back to the login page.
Or if you have a route that redirects users to a different page - you don't want users to click the back button and get redirected again.
I've also written an article on how to redirect to another page on button click.
Router componentTo use the useNavigate hook in your application, make sure the App component
in your index.js file is wrapped in a Router.
import {createRoot} from 'react-dom/client'; import App from './App'; import {BrowserRouter as Router} from 'react-router-dom'; const rootElement = document.getElementById('root'); const root = createRoot(rootElement); // ๐๏ธ Wrap your App in a Router root.render( <Router> <App /> </Router> );

Router component is in your index.js file because that's the entry point of your React application.Once your entire app is wrapped with a Router component, you can use any of
the hooks from the React router package anywhere in your components.
You can learn more about the related topics by checking out the following tutorials: