Skip to main content

Command Palette

Search for a command to run...

24) Link and NavLink

Updated
View as Markdown
  1. Linking between routes in React is typically handled using the Link and NavLink components 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.

  2. Link Component
    The Link component 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.

  3. NavLink Component
    The NavLink component is similar to the Link component 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 NavLink component adds the active class to the link when it matches the current URL, which allows you to style the active link differently.

  4. 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