To add and manage routes dynamically in React Router, you can use the Route
component and the Switch
component provided by React Router. Here is an example of how you can add and manage routes dynamically:
npm install react-router-dom
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function App() {
return (
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/about" component={About} />
</Switch>
</Router>
);
}
Route
components. Here is an example:const routes = [
{ path: '/blog', component: Blog },
{ path: '/contact', component: Contact },
];
function App() {
return (
<Router>
<Switch>
<Route exact path="/" component={Home} />
{routes.map((route, index) => (
<Route key={index} path={route.path} component={route.component} />
))}
<Route component={NotFound} />
</Switch>
</Router>
);
}
Route
with component
prop or render
prop to dynamically render components based on conditions. For example, you can conditionally render a component based on user authentication status:<Route
exact
path="/dashboard"
render={() =>
isLoggedIn ? <Dashboard /> : <Redirect to="/login" />
}
/>
With these steps, you can easily add and manage routes dynamically in your React Router application.