React.js implement menu [highlight active link]

后端 未结 2 2262
死守一世寂寞
死守一世寂寞 2021-02-15 10:10

The following React.js code renders a navbar with two links named \'about\' and \'project\'. On page load the \'about\' link is active and colored red. When the other link is

相关标签:
2条回答
  • 2021-02-15 10:44

    At this day you can use NavLink from react-router-dom. This object supports attributes as activeClassName, activeStyle, or isActive (for functions).

    import { NavLink } from 'react-router-dom';
    
    <NavLink to='about' activeClassName="active">about</NavLink>
    
    // Or specifing active style
    <NavLink to='about' activeStyle={{color: "red"}}>about</NavLink>
    
    // If you use deep routes and you need an exact match
    <NavLink exact to='about' activeClassName="active">about</NavLink>
    

    For more options read documentation: https://reacttraining.com/react-router/web/api/NavLink

    0 讨论(0)
  • 2021-02-15 10:56

    maybe slightly less verbose... in Pseudocode

    const menuItems = [
       'projects',
       'about',
    ];
    
    class MenuExample extends React.Component {
    
      _handleClick(menuItem) { 
        this.setState({ active: menuItem });
      }
    
      render () { 
        const activeStyle = { color: '#ff3333' };
    
        return (
           <div className='menu'>  
             {menuItems.map(menuItem => 
                <Link 
                 style={this.state.active === menuItem ? activeStyle : {}} 
                 onClick={this._handleClick.bind(this, menuItem)}
                > 
                  {menuItem}
                </Link>
             )}
           </div>
        );    
      }
    }
    
    0 讨论(0)
提交回复
热议问题