React Router is a library for routing in React applications. It allows you to create routes and link to them from your components. When a user clicks a link, React Router will determine which route to use and render the corresponding component.
Creating React Application: To get started, we’ll need to create a new React.js project. We can do this by running the following command:
Step 1: Create a React application using the following command.
npx create-react-app gfg
Step 2: After creating your project folder, move to it by using the following command.
cd gfg
Step 3: Start the application using the following command:
npm run start
Project Structure: Below is the structure of the project:
React Router vs Conventional Routing: React Router is a library for React that provides routing functionality. It is different from conventional routing in a few ways.
First, React Router is declarative. This means that you specify what you want your route to look like, rather than specifying how to get there. This makes it more user-friendly and easier to read.
Second, React Router is modular. This means that you can use only the features you need, rather than having to include everything in the library. This makes it more lightweight and efficient.
Third, React Router is asynchronous. This means that routes can be loaded on-demand, rather than all at once. This makes the application more responsive and efficient.
Fourth, React Router is composable. This means that you can create complex routes by combining multiple routes together. This makes the routing process more flexible.
Example: Now we are going to use React router to add routing in our app. For this, we will create a new ‘pages’ directory in our ‘src’ folder. Inside this newly created directory, we will create two JavaScript files ‘Home.js’ and ‘Data.js’ with the below content.
Home.js
import React from 'react' import { Link } from "react-router-dom" ; export default function Home() { return ( <> <div>Home - neveropen</div> <Link to= "/data" >Data</Link> </> ) } |
Data.js
import React from 'react' import { Link } from "react-router-dom" ; export default function Data() { return ( <> <div>Data</div> <Link to= "/" >Home</Link> </> ) } |
Now add the below content in ‘index.js’ file.
index.js
import ReactDOM from "react-dom" ; import { BrowserRouter, Routes, Route } from "react-router-dom" ; import Data from "./pages/Data" ; import Home from "./pages/Home" ; export default function App() { return ( <BrowserRouter> <Routes> <Route exact path= "/" element={<Home />} /> <Route path= "/data" element={<Data />}> </Route> </Routes> </BrowserRouter> ); } ReactDOM.render(<App />, document.getElementById( "root" )); |
Steps to run the application: Use the below command in the terminal to start the application.
npm start
Output: