React JS

ReactJS - Router

ReactJS - Router

Routers, also known as routing libraries, allow developers to create single-page applications that can easily handle navigation and URL changes without needing to reload the whole page or perform a redirect. This helps improve user experience by allowing them to seamlessly transition between different parts of an application while still keeping all the necessary data intact. 

Here is an example of how to use React Router to handle routing in your application

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

In this example, the BrowserRouter component is used as the top-level component for handling routing. The Link component is used to create links that navigate to different routes. The Switch component is used to render the first route that matches the current URL. The Route component is used to define the routes and to map URLs to specific components. 

You can also use useParams hook to access the parameters of a route. import { useParams } from "react-router-dom"; 

function User() { 
let { id } = useParams(); 
return <h3>ID: {id}</h3>; 
} 
function App() { 
return ( 
<Router> 
<div> 
<nav> 
<Link to="/">Home</Link> 
<Link to="/user/42">User 42</Link> 
</nav> 
<Switch> 
<Route path="/user/:id"> 
<User /> 
</Route> 
<Route path="/"> 
<Home /> 
</Route> 
</Switch> 
</div> 
</Router> 
); 
}

 

Top course recommendations for you

    Graphs in Python
    1 hrs
    Beginner
    2.7K+ Learners
    4.5  (84)
    Python Tkinter
    1 hrs
    Beginner
    5.3K+ Learners
    4.54  (494)
    Database Normalization
    1 hrs
    Beginner
    5.4K+ Learners
    4.67  (546)
    Pattern Program in Java
    2 hrs
    Beginner
    3.5K+ Learners
    4.42  (64)
    DML Statements
    1 hrs
    Beginner
    4.6K+ Learners
    4.47  (450)
    GCD of Two Numbers
    2 hrs
    Beginner
    1.1K+ Learners
    4.62  (34)
    Language Translator in Python
    2 hrs
    Intermediate
    3K+ Learners
    4.64  (109)
    Matrix Multiplication in C
    1 hrs
    Beginner
    3.8K+ Learners
    4.45  (272)
    Waterfall Model
    1 hrs
    Beginner
    5.9K+ Learners
    4.47  (628)