How to Update Routes in React Router
Updating router routes in React is a fundamental task when managing navigation and page structure in modern web applications. This article provides a straightforward guide on how to update and configure routes using React Router (v6+), covering static route updates, dynamic route conditional changes, and programmatic navigation updates.
Updating Static Routes
In modern React applications using React Router v6, routes are
typically defined using a data router like
createBrowserRouter. To add, remove, or modify a route, you
need to update the route definition array passed to this function.
Here is how you update your route configuration file:
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import Contact from './pages/Contact'; // New page to add
const router = createBrowserRouter([
{
path: "/",
element: <Home />,
},
{
// Updating an existing route path or component
path: "/about-us",
element: <About />,
},
{
// Adding a new route
path: "/contact",
element: <Contact />,
}
]);
export default function App() {
return <RouterProvider router={router} />;
}If you are using the older JSX-only declaration style, you update the
<Route> components inside the
<Routes> parent component:
import { Routes, Route } from 'react-router-dom';
function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about-us" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
);
}Updating Routes Dynamically (Conditional Routing)
Often, you need to update accessible routes based on the application state, such as whether a user is logged in. You can achieve this by conditionally rendering your routes.
import { createBrowserRouter, RouterProvider, Navigate } from 'react-router-dom';
const App = ({ isAuthenticated }) => {
const router = createBrowserRouter([
{
path: "/",
element: <Home />,
},
// This route updates dynamically based on the authentication state
{
path: "/dashboard",
element: isAuthenticated ? <Dashboard /> : <Navigate to="/login" />,
},
{
path: "/login",
element: <Login />,
}
]);
return <RouterProvider router={router} />;
};Updating the Active Route Programmatically
To update the user’s current URL route dynamically within a component
(for example, redirecting after a form submission), use the
useNavigate hook.
import { useNavigate } from 'react-router-dom';
function LoginForm() {
const navigate = useNavigate();
const handleSubmit = (event) => {
event.preventDefault();
// Perform login logic...
// Update the route to the dashboard page
navigate('/dashboard');
};
return (
<form onSubmit={handleSubmit}>
<button type="submit">Log In</button>
</form>
);
}