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.3K+ Learners
    4.43  (56)
    Trees in Python
    2 hrs
    Beginner
    2.1K+ Learners
    4.64  (44)
    Python Tkinter
    1 hrs
    Beginner
    4.2K+ Learners
    4.55  (280)
    Database Normalization
    1 hrs
    Beginner
    4K+ Learners
    4.6  (213)
    Pattern Program in Java
    2 hrs
    Beginner
    3K+ Learners
    4.51  (49)
    DML Statements
    1 hrs
    Beginner
    3.7K+ Learners
    4.53  (245)
    GCD of Two Numbers
    2 hrs
    Beginner
    979 Learners
    4.63  (30)
    Language Translator in Python
    2 hrs
    Intermediate
    2.4K+ Learners
    4.66  (65)
    Matrix Multiplication in C
    1 hrs
    Beginner
    3.3K+ Learners
    4.47  (132)
    Waterfall Model
    1 hrs
    Beginner
    4.7K+ Learners
    4.46  (335)