📜  NavLink (1)

📅  最后修改于: 2023-12-03 15:03:09.082000             🧑  作者: Mango

NavLink

Introduction

NavLink is a component in React Router that provides a navigation link which updates the URL in the address bar and adds an active CSS class to the rendered element when it matches the current URL.

Syntax

The basic syntax of using NavLink component is as follows:

<NavLink to="/path" activeClassName="active">{linkText}</NavLink>
Props

NavLink component accepts the following props:

  1. to (string or object)

    • Specifies the path or location to navigate to when the link is clicked. This can be a string representing the URL or an object for complex route matching.
  2. activeClassName (string)

    • Indicates the CSS class name to be used when the link is active and matches the current URL.
  3. isActive (function)

    • A function that determines whether the link should be considered active. It receives the match object containing information about the current URL and can return a boolean value indicating whether the link is active.
  4. exact (bool)

    • If true, the active CSS class will only be applied if the current URL exactly matches the link's destination.
  5. strict (bool)

    • If true, the active CSS class will also be applied if the current URL is a prefix of the link's destination.
  6. location (object)

    • Allows specifying the current location object instead of using the actual current location. Useful in cases where you want to override the location value for testing purposes.
Usage

Here's an example of using NavLink to create navigation links in a React application:

import { NavLink } from 'react-router-dom';

function Navigation() {
  return (
    <nav>
      <NavLink to="/" exact activeClassName="active">Home</NavLink>
      <NavLink to="/about" activeClassName="active">About</NavLink>
      <NavLink to="/contact" activeClassName="active">Contact</NavLink>
    </nav>
  );
}

In this example, clicking on the links will update the URL and add the "active" class to the currently active link.

Additional Notes
  • NavLink is mainly used with React Router, so make sure to install and import React Router components before using NavLink.
  • NavLink component is a wrapper around the Link component in React Router, providing additional functionality for navigation links.