phen0menon
phen0menon

Reputation: 2462

React implement active menu item in sidebar

I'm using React version 16.6.3. I need some help to implement active menu item in sidebar. I need to do this thing: when the user clicks on any <li> in sidebar, the <li> must become active (for example, it gets class "active").

If the <li> is active and have treeview class, then, inside it, set to <ul> class "show" (if any)

Here's the code:

import React , { Component } from "react"

export default class Sidebar extends Component {
  constructor(props) {
    super(props);
    this.state = { 'activeItem': 0 }
  }
  render() {
    return (
      <div className="main-sidebar">
        <section className="sidebar">
          <ul className="sidebar-menu tree">
            <li className="nav-divider"></li>
            <li className="header">PERSONAL</li>

            <li>
              <a href="#">
                <span>Dashboard</span>
              </a>
            </li>

            <li className="treeview">
              <a href="#">
                <span>Application</span>
              </a>
              <ul class="treeview-menu">
                <li><a href="">Chat app</a></li>
                <li><a href="">Project</a></li>
                <li><a href="">Contact / Employee</a></li>
              </ul>
            </li>

            <li className="treeview">
              <a href="#">
                <span>Application</span>
              </a>
            </li>
          </ul>
        </section>
      </div>
    )
  }
}

Upvotes: 0

Views: 1909

Answers (2)

windmaomao
windmaomao

Reputation: 7680

The first question you should ask yourself is (if not always) how you store the data of the user selection. You might have multiple activeItem because this is a tree, ex. multiple branches can be open or close at the same time. You need to look for a data structure to hold that thinking first.

Here's a simple one, give each item an id/key, <li key="1-0-0"> and then you can track onChange event of this li and then inside onChange you can use a flat array structure to store the current state of this simple tree. For example, {'1-0-0': true }

There're lots of different ways to do data part, the above one is a simple idea to get you started. And after that, based on the captured data, you can then update the children attribute of each node, ex. <li className={ getNodeAttr('1-0-0')> assuming getNodeAttr is a utility function that give you back the class name string given the node name.

Upvotes: 1

Mos&#232; Raguzzini
Mos&#232; Raguzzini

Reputation: 15871

You should not bind active state on a navigation sidebar because if a user type a route directly in a browser the menu item won't be highlighted. Instead, try to bind the active state to the route with NavLink (if you use react-router):

ref: https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/NavLink.js

Upvotes: 0

Related Questions