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.8K+ Learners
    4.52  (89)
    Python Tkinter
    1 hrs
    Beginner
    5.4K+ Learners
    4.55  (544)
    Database Normalization
    1 hrs
    Beginner
    5.6K+ Learners
    4.67  (633)
    Pattern Program in Java
    2 hrs
    Beginner
    3.5K+ Learners
    4.44  (70)
    DML Statements
    1 hrs
    Beginner
    4.7K+ Learners
    4.48  (470)
    GCD of Two Numbers
    2 hrs
    Beginner
    1.1K+ Learners
    4.64  (36)
    Language Translator in Python
    2 hrs
    Intermediate
    3K+ Learners
    4.65  (113)
    Matrix Multiplication in C
    1 hrs
    Beginner
    3.8K+ Learners
    4.45  (273)
    Waterfall Model
    1 hrs
    Beginner
    6K+ Learners
    4.49  (734)