React Router Tutorial in One Video in Hindi
React Router
• Collection of navigational components
– Enables navigation among views
– Router components, route matching components and
navigation components
• Uses browser-based bookmarkable URLs as an instruction
to navigate to a client-generated view in your web app
– Can also pass along optional parameters
Web App Routing
• Install react-router-dom
• Router component: <BrowserRouter>
– Creates specialized history object
– Also <HashRouter> if you are using a static file server
– Enclose your app in BrowserRouter
Route Matching
• Route matching components: <Route> and <Switch>
– <Route>’s path prop enables specification of the current location’s
pathname
– <Route>’s component prop specifies the corresponding view for the
location
– Using exact attribute ensures that the path must be exactly matched
– <Redirect> enables the default route specification
– <Switch> enables grouping together several routes
• Will iterate over all its children and find the first one that matches the path
Navigation
• Navigation is supported through the <Link>
and <NavLink> components:
– <Link> creates links in your application
• Will render as <a> in the HTML
– <NavLink> also attaches the active class to the link
when its prop matches the current location
Menu.js Component Code
import React from 'react';import './Menu.css';
import { Link } from 'react-router-dom';
const Menu = () =>{
return(
<div>
<nav className="navstyle">
<ul>
<li> <Link to=""> Home </Link> </li>
<li> <Link to="About"> About </Link> </li>
<li> <Link to="Contact"> Contact </Link> </li>
</ul>
</nav>
</div>
)
}
export default Menu;
Menu.css File Code
*{ margin: 0; padding: 0; }.navstyle{
width: 100%; height: 100px; background: #6ab04c; color: white;
}
.navstyle ul {
height: 100px;
display: flex;
justify-content: space-around;
align-items: center;
}
.navstyle ul li{
list-style: none;
text-transform: uppercase;
color: white;
}
.navstyle ul li a{
color: white;
}
App.js Component Code
import React from 'react';
import './App.css';
import './Home.css';
import About from './About';
import Menu from './Menu';
import Contact from './Contact';
import { BrowserRouter, Route } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Menu />
<switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</switch>
</BrowserRouter>
);
}
const Home = () => {
return (
<div className="homestyle">
<h2> This is the Home Page. </h2>
</div>
)
}
export default App;