📜  NavLink - Javascript (1)

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

NavLink - Javascript

NavLink is a package in JavaScript that provides a way to render navigation links that play nicely with React Router.

Features
  • Renders navigation links that are aware of the current route and can automatically apply an "active" class when the link is active.
  • Automatically handles nested routes and applies the "active" class to parent links when one of their descendants is active.
  • Can use any component for the link, not just a standard tag.
  • Provides many customization options, including custom active class names, custom comparison functions, and more.
Installation

You can install NavLink using npm or yarn:

npm install react-router-dom
yarn add react-router-dom
Usage

To use NavLink in your React application, first import it from react-router-dom:

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

Then, you can use the NavLink component just like you would use a regular tag:

<NavLink to="/" activeClassName="active">
  Home
</NavLink>

Here, the to prop specifies the target route, and activeClassName specifies the name of the CSS class to apply when the link is active.

You can also nest NavLink components for nested routes:

<NavLink to="/parent" activeClassName="active">
  Parent
  <ul>
    <li>
      <NavLink to="/parent/child1" activeClassName="active">
        Child 1
      </NavLink>
    </li>
    <li>
      <NavLink to="/parent/child2" activeClassName="active">
        Child 2
      </NavLink>
    </li>
  </ul>
</NavLink>

In this example, the "active" class will be applied to both the "Parent" link and the appropriate child link when one of the child routes is active.

Conclusion

NavLink is a powerful tool for creating navigation links in React applications. With its advanced features and flexible customization options, it makes it easy to create navigation menus that are intuitive and easy to use.