React Router v4 setting activeClass on parent

前端 未结 4 1102
猫巷女王i
猫巷女王i 2021-01-17 16:13

Not too familiar with react router, but I need the functionality of the NavLink to set the active class on the parent li element, and not the a ele

4条回答
  •  盖世英雄少女心
    2021-01-17 16:53

    In v4 after lots of tries I did.

    Here my working code.

    import React, { Component } from "react";
    import logo from "../../logo.svg";
    import { Link, withRouter } from "react-router-dom";
    import PropTypes from "prop-types";
    
    class Navbar extends Component {
      static propTypes = {
        match: PropTypes.object.isRequired,
        location: PropTypes.object.isRequired,
        history: PropTypes.object.isRequired
      };
    
      state = {};
    
      getNavLinkClass = path => {
        return this.props.location.pathname === path
          ? "nav-item active"
          : "nav-item";
      };
      render() {
        return (
          
        );
      }
    }
    
    export default withRouter(Navbar);
    

    Demo working Code Sandbox

提交回复
热议问题