React Router is a popular library for handling routing in React applications. It allows you to define routes in your application and navigate between different components or views without reloading the page.
Here’s a step-by-step example of how to set up and use React Router in a simple React application:
Install React Router:
First, you need to install React Router.
npm install react-router-dom
Create Components:
Next, create the components for Home
, About
, and Contact
.
//home.jsx
import React from 'react';
function Home() {
return <h2>Home</h2>;
}
Now, create the About.jsx component
// src/components/About.jsx
import React from 'react';
function About() {
return <h2>About</h2>;
}
export default About;
Now, create the Contact.jsx component
// src/components/Contact.jsx
import React from 'react';
function Contact() {
return <h2>Contact</h2>;
}
export default Contact;
Set up the Router:
In your src
directory, create a new file headerMenu.js
x (if it doesn’t already exist) and set up the router.
import React from "react";
import {Link} from 'react-router-dom';
export default function HeaderMenu(){
return (
<>
<nav className="navbar navbar-expand-lg bg-primary">
<div className="container-fluid">
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav me-auto mb-2 mb-lg-0">
<li className="nav-item ">
<Link className="nav-link active text-light" aria-current="page" to="/">Home</Link>
</li>
<li className="nav-item">
<Link className="nav-link text-light" to="/about-us">AboutUs</Link>
</li>
<li className="nav-item">
<Link className="nav-link text-light" to="/contact-us">ContactUs</Link>
</li>
</ul>
</div>
</div>
</nav>
</>
)
}
In the above example, we use Link instead of anchor (a) tag and we use to instead of href.
create Router.Example.jsx
import React from "react";
import HeaderMenu from "./HeaderMenu";
import {BrowserRouter,Routes,Route} from 'react-router-dom'
import Aboutus from "./About";
import ContactUs from "./Contact";
import Home from "./Home";
export default function RoutingExample(){
return (
<>
<BrowserRouter>
<HeaderMenu/>
<Routes>
<Route path="/" element={<Home/>}></Route>
<Route path="/about-us" element={<Aboutus/>}></Route>
<Route path="/contact-us" element={<ContactUs/>}></Route>
</Routes>
</BrowserRouter>
</>
)
}
This simple example demonstrates the basic usage of React Router. Here’s a brief explanation of the key parts:
BrowserRouter
(aliased as Router
): Wraps your application and enables routing.
Link
: Used to create navigation links.
Switch
: Renders the first child <Route>
that matches the location.
Route
: Defines a route and the component to render when the route matches.