To create nested routes in React Router, you can use the Switch
and Route
components from the react-router-dom
library. Here's a step-by-step guide on how to create nested routes:
react-router-dom
if you haven't already:npm install react-router-dom
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
Switch
component, using the Route
component for each route:function App() {
return (
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/services" component={Services} />
<Route path="/contact" component={Contact} />
</Switch>
</Router>
);
}
function Services() {
return (
<div>
<h2>Our Services</h2>
<Switch>
<Route path="/services/web-design" component={WebDesign} />
<Route path="/services/seo" component={SEO} />
</Switch>
</div>
);
}
function WebDesign() {
return <h3>Web Design Services</h3>;
}
function SEO() {
return <h3>SEO Services</h3>;
}
With this setup, when a user navigates to /services/web-design
, the WebDesign
component will be rendered, and when they navigate to /services/seo
, the SEO
component will be rendered. This allows you to create nested routes within your application using React Router.