Introduction to Topic and Actualization

Welcome back! Our journey today brings us into the heart of React, with a focus on NavLink Components. These components guide users around websites — think of them as the navigation system on a spaceship! Another crucial part of this ship is the Link — a less advanced sibling of NavLink. As we delve deeper, we will learn how to enhance these with appealing styles and helpful attributes. But before we get started, ensure that React Router DOM v6 is ready in your project, as its unique features will be our guide today.

Introduction to NavLink Components

In React routing, NavLink is one way to navigate different routes, acting like an advanced Link. Here's how:

import { BrowserRouter as Router, NavLink } from 'react-router-dom'; 

const Nav = () => (
  <Router>
    <NavLink to="/home" activeClassName="active">Home</NavLink>
    <NavLink to="/about" activeClassName="active">About</NavLink>
  </Router>
);

Think of NavLinks as doors on our spaceship that lead us to different areas like Home or About. Each click transports us to the respective spaces within the site.

NavLink vs Link

NavLink's superpower is that it offers user feedback—it styles "active" links. An 'active' link is akin to the room we're in. So, if we're in the 'About' room, the 'About' NavLink gets styled as 'active':

import { BrowserRouter as Router, Link, NavLink } from 'react-router-dom'; 

function Nav() {
  return (
    <Router>
      <Link to="/home">Home</Link>
      <NavLink to="/about" activeClassName="active">About</NavLink>
    </Router>
  );
}

The attribute activeClassName="active" in NavLink indicates this. Upon visiting '/about', NavLink applies the class 'active' to our About link. Delightful, isn't it?

Styling NavLink Components

Ships ought to look cool, right? NavLinks are no different: we style them using CSS:

import { BrowserRouter as Router, NavLink } from 'react-router-dom'; 
import './App.css'; 

function Nav() {
  return (
    <Router>
      <NavLink to="/home" className="nav-link" activeClassName="active">Home</NavLink>
      <NavLink to="/about" className="nav-link" activeClassName="active">About</NavLink>
    </Router>
  );
}

In our CSS file, we deck out the .nav-link and .active tags with unique styles.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal