Open In App

How is React Router is different from conventional routing ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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.

Prerequisites:

Steps to Create the React Application And Installing Module:

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: Installing packages using the following command:

npm install react-router-dom

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.17.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}

React Router is Different from Conventional routing:

React Router, a declarative and modular library for React, simplifies routing by specifying route appearance rather than navigation details. Its modularity allows selective feature usage, enhancing efficiency. Additionally, React Router’s asynchronous nature supports on-demand loading of routes, promoting responsiveness, and its composable design enables the creation of intricate routes by combining multiple components.

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.

Javascript




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"));


Javascript




import React from 'react'
import { Link } from "react-router-dom";
 
export default function Home() {
    return (
        <>
            <div>Home - GeeksforGeeks</div>
            <Link to="/data">Data</Link>
        </>
    )
}


Javascript




import React from 'react'
import { Link } from "react-router-dom";
 
export default function Data() {
    return (
        <>
            <div>Data</div>
            <Link to="/">Home</Link>
        </>
    )
}


Steps to run the application: Use the below command in the terminal to start the application.

npm start

Output:



Last Updated : 28 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads