Open In App

What is React Router?

React Router is like a traffic controller for your React application. Just like how a traffic controller directs vehicles on roads, React Router directs users to different parts of your app based on the URL they visit. So, when you click on a link or type a URL in your browser, React Router decides which part of your React app to show, making it easy to create seamless and interactive single-page applications.

Key Features of React Router:

Steps to Create React App and Installing React Router:

Step 1: Create a React application using the following command:



npx create-react-app foldername

Step 2: After creating your project folder i.e. folder name, move to it using the following command:

cd foldername

Step 3: Install React Router package.



npm install react-router-dom

Project Structure:

Example Code: Write the following code in the respective files.




// App.js
import React from 'react';
import {
    BrowserRouter as Router,
    Routes,
    Route,
    Link
} from 'react-router-dom';
import Home from './Home';
import About from './About';
 
function App() {
    return (
        <Router>
            <div>
                <nav>
                    <ul>
                        <li>
                            <Link to="/">Home</Link>
                        </li>
                        <li>
                            <Link to="/about">About</Link>
                        </li>
                    </ul>
                </nav>
 
                <Routes>
                    <Route path="/" element={<Home />} />
                    <Route path="/about" element={<About />} />
                </Routes>
            </div>
        </Router>
    );
}
 
export default App;




// Home.js
import React from 'react'
 
const Home = () => {
    return (
        <div>Home</div>
    )
}
 
export default Home




// About.js
import React from 'react'
 
const About = () => {
    return (
        <div>About</div>
    )
}
 
export default About

Start your application using the following command.

npm start

Output:

Routing to Different Components


Article Tags :