24) Link and NavLink
Linking between routes in React is typically handled using the
LinkandNavLinkcomponents provided by React Router. These components allow you to create navigational links that users can click to navigate to different routes within your application without triggering a full page reload.Link Component
TheLinkcomponent is used to create hyperlinks in your React application. It is similar to the HTML<a>tag but is specifically designed to work with React Router.import React from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; const Home = () => <h2>Home</h2>; const About = () => <h2>About</h2>; const App = () => ( <Router> <div> <nav> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/about">About</Link></li> </ul> </nav> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> </div> </Router> ); export default App;In this example, clicking on the "Home" or "About" links will navigate to the respective routes without reloading the page.
NavLink Component
TheNavLinkcomponent is similar to theLinkcomponent but provides additional functionality to apply active styles to the link when it matches the current URL.import React from 'react'; import { BrowserRouter as Router, Route, NavLink } from 'react-router-dom'; const Home = () => <h2>Home</h2>; const About = () => <h2>About</h2>; const App = () => ( <Router> <div> <nav> <ul> <li><NavLink exact to="/" activeClassName="active">Home</NavLink></li> <li><NavLink to="/about" activeClassName="active">About</NavLink></li> </ul> </nav> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> </div> </Router> ); export default App;In this example, the
NavLinkcomponent adds theactiveclass to the link when it matches the current URL, which allows you to style the active link differently.When to Use What
Use Link,
i) Buttons
ii) Redirect links
iii) Anywhere navigation is needed
Use NavLink,
i) Navbar
ii) Sidebar
iii) menus
iv) Tabs
v) Breadcrumbs