Published 15 Feb, 2022

How to apply active menu in Link in react?

Category React
Modified : Nov 30, 2022

React JS is an elegant Javascript library for creating building user interfaces based on components. It's extensively popular and makes your frontend expressive, manageable, fluid and user friendly.

There are 2 suggested solutions in this post and each one is listed below with a detailed description on the basis of most helpful answers as shared by the users. I have tried to cover all the aspects as briefly as possible covering topics such as Reactjs and a few others. I have categorized the possible solutions in sections for a clear and precise explanation. Please consider going through all the sections to better understand the solutions.

Solution 1

You can use NavLink component from react-router. A special version of the Link that will add styling attributes to the rendered element when it matches the current URL.

<NavLink to="/dashboard" activeClassName="active">
  Dashboard
</NavLink>

You can also connect withRouter. This gives the your component access to this.props.history where is the current route.


Solution 2

Using React Hooks:

import React,  from 'React'

const Menu = () => {

  const [activeMenu, setActiveMenu] = useState()

  return (
        <ul
            className="nav nav-pills nav-sidebar flex-column"
            data-widget="treeview"
            role="menu"
            data-accordion="false"
        >
            <li className="nav-item has-treeview menu-open">
                <Link
                    id="dashboard"
                    to="/dashboard"
                    className=
                    onClick={() => { setActiveMenu('dashboard') }}
                >
                    <i className="nav-icon fa fa-home"></i>
                    <p>Dashboard</p>
                </Link>
            </li>
            <li className="nav-item has-treeview menu-open">
                <Link
                    id="review"
                    to="/review"
                    className=
                    onClick={() => { setActiveMenu('review') }}
                >
                    <i className="nav-icon fa fa-comments"></i>
                    <p>Reviews</p>
                </Link>
            </li>
        </u>
    )
}

Final Words

These were some of the solutions I found worth sharing. There are well a lot of alternatives around but I have tried and tested these for a while now and so I found them worth sharing here. I hope it fulfills the purpose you're looking to utilize them for.

Hey! It compiles! Ship it!
Unknown
Tags: Reactjs