How to create nested routes in React Router?

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:

  1. Install react-router-dom if you haven't already:
npm install react-router-dom
  1. Import the necessary components in your main App component:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
  1. Define your nested routes within the 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> ); }
  1. Create the components for each route that you defined. Here's an example of a nested route structure:
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.