React Router is a popular library for managing routing in React applications. When defining routes in React Router, two of the most commonly used props are path
and exact path
.
These props control how the router matches URLs to routes. It allows developers to define the navigation routes of an application, enabling users to move between pages and components without reloading the entire page. When working with React Router, it's essential to understand the difference between exact path
and path
, two of its core features.
path
prop with the exampleThe path
prop is used to specify the URL pattern that a route should match. For example, if we want to match the URL /blog/123
, we can define a route with a path
prop of /blog/:id
, where :id
is a parameter that matches any value in the URL.
<Route path="/blog/:id" component={BlogPost} />
This will render the BlogPost
component when the user navigates to the /blog
path.
However, there's a potential problem with this approach. If we define another route with a path that starts with /BlogPost
, like /BlogPost/contact
, React Router will match both routes. This is because React Router uses a "starts with" approach to matching paths. This is where exact path
comes in.
exact
path
prop with exampleThe exact path
prop indicates that a route should only match an exact URL. For example, if we have two routes defined like this:
<Route exact path="/" component={Home} /><Route exact path="/about" component={About} />
Line 1: The first route with an exact prop of true will only match the root URL /
.
Line 2: Now, if the user navigates to /about/contact
, React Router will not match this route, and will instead look for another route that matches the URL.
path
vs exact path
Let’s look at an example of path
vs exact path
below:
import React from 'react'; import ReactDOM from 'react-dom'; import App from './app.js'; require('./style.css'); ReactDOM.render( <App />, document.getElementById('root') );
We can see that this time only the Home
component renders.
The path
prop defines a URL pattern that a route should match, while the exact path
prop indicates that a route should only match an exact URL. We can combine these props to create more complex routing behavior in our application.
Free Resources