React Router DOM:
React Router DOM is a library used in React applications to navigate between different pages or views without reloading the entire webpage.
In a traditional website, clicking a link may load a completely new HTML page from the server. In a React single-page application (SPA), React Router DOM allows us to display different components based on the URL.
For example, an e-commerce website may contain:
- / — Home page
- /products — Products page
- /cart — Cart page
- /login — Login page
React Router DOM helps us connect these URLs to their corresponding React components.
Why do we need React Router DOM?
React itself does not provide built-in routing for navigating between different URL paths.
Without a routing library, we would need to manage URL changes and which components to display ourselves.
React Router DOM makes this process easier by providing features such as:
- Navigation: Move between pages without a full-page reload.
- Routing: Display specific components based on the URL.
- Dynamic routes: Pass values through URLs, such as /users/10.
- Nested routes: Display child pages inside a parent layout.
- Programmatic navigation: Navigate to another route using code.
- Route parameters: Access dynamic values from the URL.
How to install React Router DOM?
Install React Router DOM:
npm install react-router-dom
React Router DOM components:
BrowserRouter:
- BrowserRouter enables client-side routing using the browser's URL and History API.
- It usually wraps the main application so that routing features are available throughout the component tree.
Routes:
Routes groups the route definitions in your application. It selects the best matching route for the current URL.
Route:
Route connects a URL path to the component that should be rendered.
For example:
<Route path="/about" element={<About />} />
When the URL matches /about, the About component is displayed.
Link:
Link is used to navigate between routes without triggering a full-page reload.
<Link to="/about">About</Link>
useNavigate:
useNavigate is a hook that allows us to navigate programmatically, such as after a successful login.
useParams:
useParams is a hook used to access dynamic route parameters.
For example, for /users/10, it can return the value "10" for the id parameter.
Top comments (0)