In React Router, the <Switch>
component is used to group a set of <Route>
components together and only render the first route that matches the current URL. This is useful when you have multiple routes that could potentially match the current URL, and you want to ensure that only one of them is rendered at a time.
Here’s an example of how to use the <Switch>
component:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
function App() {
return (
<Router>
<div>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</nav>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Route path="*" component={NotFound} />
</Switch>
</div>
</Router>
);
}
In this example, the <Switch>
component is used to group the <Route>
components together. The <Route>
components are defined as children of the <Switch>
component, and they will only be rendered if their path
prop matches the current URL.
In this example, if the user navigates to the root path ‘/’, the Home
component will be rendered since it has the exact
prop. If the user navigates to ‘/about’ or ‘/contact’ the corresponding component will be rendered. And if the user navigates to any other path, the NotFound
component will be rendered, since the last <Route path="*" component={NotFound} />
has a catch-all path *
and it will match any path that doesn’t match the other routes.
It’s important to note that the <Route>
components should be in the order of most specific to least specific, meaning the catch-all routes should be the last one to be defined.