Router, Link and NavLink
React Router helps us to route through pages using URL without page refresh.
Router sends http request to server for getting content in response from the server which make application application slow and break customer flow.
Use below command to install React Router as npm install react-router-dom:
Example:
Below is an React Router example to route pages hitting same on browser.
* is wildcard entry and it will come in picture if no path gets match.
import React from "react";
import { BrowserRouter, Routes, Route} from "react-router-dom";
function HomePage() {
return <div>Home Page</div>;
}
function ProductCategoryPage() {
return <div>Product Category Page</div>;
}
function ProductPage() {
return <div>Product Page</div>;
}
export default function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<HomePage />}></Route>
<Route path="/category" element={<ProductCategoryPage />}></Route>
<Route path="/product" element={<ProductPage />}></Route>
<Route path="*" element={<HomePage />}></Route>
</BrowserRouter>
</Router>
);
}
<Router> is a root element tag for all <Routes>. <Routes> tag contains multiple <Route> having path and element as an attribute.
OUTPUT:
Link
Link is used to redirect through pages on click.
Let’s try to understand why we require to have <Link> tag if we are already having <a> tag in place. <a> tag always refresh a page while navigating from one page to another.
Link belongs to react-router-dom package.
Syntax:
<Link to="/">Home</Link>
Example:
Below is an example of Link for traversing from one page to another without page refresh.
import { BrowserRouter, Routes, Route, Link, Layout } from "react-router-dom";
import React from "react";
function HomePage() {
return <div>Home Page</div>;
}
function ProductPage() {
return <div>Product Page</div>;
}
export default function App() {
return (
<>
<BrowserRouter>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/product">Product</Link></li>
</ul>
<Routes>
<Route path="/" element={<HomePage />}></Route>
<Route path="/product" element={<ProductPage />}></Route>
</Routes>
</BrowserRouter>
</>
);
}
OUTPUT
Note:
In place of <Link> we can use <NavLink> which helps us to add style attribute to html element.
Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.