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">

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 (
            className="nav nav-pills nav-sidebar flex-column"
            <li className="nav-item has-treeview menu-open">
                    onClick={() => { setActiveMenu('dashboard') }}
                    <i className="nav-icon fa fa-home"></i>
            <li className="nav-item has-treeview menu-open">
                    onClick={() => { setActiveMenu('review') }}
                    <i className="nav-icon fa fa-comments"></i>

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!
Tags: Reactjs