Blog>
Snippets

Defining Nested Routes with React Router

Provide an example of how to define nested routes in a React application using React Router, focusing on the hierarchical composition of `<Route>` components.
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
First, import the necessary components from react-router-dom to enable routing.
function App() {
  return (
    <Router>
      <Switch>
        <Route path="/" exact component={Home} />
        <Route path="/about" component={About} />
      </Switch>
    </Router>
  );
}
Defines the main App component with a Router. Contains a root route to Home and an about page route.
const About = () => (
  <div>
    <h2>About Page</h2>
    <Switch>
      <Route path="/about/team" component={Team} />
      <Route path="/about/company" component={Company} />
    </Switch>
  </div>
);
Defines the About component with nested routes for team and company pages.
const Team = () => <h3>Team Page</h3>;
const Company = () => <h3>Company Page</h3>;
Defines simple components for the nested routes under About.