Usage of Route
To define routes and associate components with specific paths, you use the Route component. Below are the implementation of Routes form react-router-dom v6.
Example 1: Creating default and About page Route
In this example, we define two routes, one for the home page (path=”/”) and another for the about page (path=”/about”). When the URL matches these paths, the corresponding component (Home or About) is rendered.
Javascript
import React from "react" ; import { BrowserRouter as Router, Route, Routes } from "react-router-dom" ; const Home = () => <div>Home Page</div>; const About = () => <div>About Page</div>; const App = () => { return ( <Router> <Routes> <Route path= "/" element={<Home />} /> <Route path= "/about" element={<About />} /> </Routes> </Router> ); }; export default App; |
Example 2: Creating Home and About Page Route with Navigation
In this working example, here we will use the BrowswerRouter and Route and demonstrate that how its works, here we will create two component home and about, and we will set up the routing, so that when we click on the home or about it will go to that route.
Javascript
import React from "react" ; import { BrowserRouter, Routes, Route, Link } from "react-router-dom" ; function App() { // Home component const Home = () => ( <div> <h1>Home Page</h1> <p>Welcome to the home page!</p> </div> ); // About component const About = () => ( <div> <h1>About Page</h1> <p>This is the about page.</p> </div> ); return ( <BrowserRouter> <div> <nav> <ul> <li> <Link to= "/" >Home</Link> </li> <li> <Link to= "/about" >About</Link> </li> </ul> </nav> { /* Route components are rendered if the path matches the current URL */ } <Routes> <Route path= "/" element={<Home />} /> <Route path= "/about" element={<About />} /> </Routes> </div> </BrowserRouter> ); } export default App; |
Output:
Explain the purpose of the BrowserRouter and Route components.
React Router proves to be a robust library that empowers client-side routing in React applications. At its core, two pivotal components, BrowserRouter and Route, play key roles. In this article, we’ll explore into the functions and application of these components, providing insights into how they streamline navigation and routing within your React application.
We will discuss about the following features of BrowserRouter and Route Components
Table of Content
- Purpose of BrowserRouter
- Purpose of Route
- Usage of BrowserRouter
- Usage of Route
- Advantages of BrowserRouter and Route