Tips for adding an active class when a link is clicked

I am working on a Sidebar component and need to apply the active_class_link style to the DIV element when the onClick() event occurs. Although I have set up the function, I am unsure how to apply this for each DIV within my component.

The desired behavior is that when one link is clicked, the active_class_link style should be removed from any previously active div and added to the newly clicked link.

Here is an overview of my Sidebar component:

import React from 'react';
import { Link } from 'react-router-dom';
import './Sidebar.css';

const Sidebar = ({ sidebarOpen, closeSidebar, handleLogout }) => {
  let logoUrl = JSON.parse(localStorage.getItem('app_icon'));

  const handleActive = (e) => {
    console.log('Adding active to ', e.target);
  };

  return (
    <div id='sidebar' className={sidebarOpen ? 'sidebar-responsive' : ''}>
      <div className='sidebar_title'>
        <div className='sidebar_img'>
          <img src={logoUrl} alt='logo' />
          <h1>Admin Panel</h1>
        </div>
        <i className='fa fa-times' id='sidebaricon' onClick={closeSidebar}></i>
      </div>
      <div className='sidebar_menu'>
        <div className='sidebar_link ' onClick={(e) => handleActive(e)}>
          <i className='fa fa-home'></i>
          <Link to='/home'>Dashboard</Link>
        </div>
        <h2>MNG</h2>

        // Additional sidebar links here

        <div
          className='dev'
          style={{ position: 'absolute', bottom: '20px', left: '8px' }}
        >
          <h3 style={{ color: '#51c4d3' }}>
            Developed by{' '}
            <i
              className='far fa-thumbs-up'
              style={{ fontSize: '1.6rem', marginLeft: '4px' }}
            ></i>
          </h3>
          <h2 style={{ color: '#b0efeb' }}>Codeven Solution</h2>
        </div>
      </div>
    </div>
  );
};

export default Sidebar;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

The styles for the active Class Link are defined as follows:

.active_class_link {
  border-radius: 6px;
  background: #19456b;
  color: #a3ddcb;
}

If you have any suggestions or solutions, please feel free to share them. Thank you!

Answer №1

By switching from using Link to NavLink, you can seamlessly apply an active class without any hassle.

<NavLink to='/home' activeClassName="active_class_link">Dashboard</Link>

Answer №2

Note: Be sure to read Sean's response below regarding the use of <NavLink/> components. It appears that option could have been utilized instead. If manual adjustments are necessary, my initial response stands, though I believe Sean's suggestion would be more beneficial...

By structuring your .sidebar-menu items based on data, managing the active state becomes simpler. You could implement something along these lines:

import React from 'react';
import { Link } from 'react-router-dom';
import './Sidebar.css';

const Sidebar = ({ sidebarOpen, closeSidebar, handleLogout }) => {
  let logoUrl = JSON.parse(localStorage.getItem('app_icon'));
  const [activeLink, setActiveLink] = React.useState(null);

  const links = [
    {
        id: 0,
        faClass: 'fa fa-home',
        url: '/home',
        title: 'Dashboard',
    },
    {
        id: 1,
        faClass: 'fas fa-user-cirlce',
        url: '/profile',
        title: 'Profile'
    },
    // etc ...
  ];

  return (
    <div id='sidebar' className={sidebarOpen ? 'sidebar-responsive' : ''}>
      <div className='sidebar_title'>
        <div className='sidebar_img'>
          <img src={logoUrl} alt='logo' />
          <h1>Admin Panel</h1>
        </div>
        <i className='fa fa-times' id='sidebaricon' onClick={closeSidebar}></i>
      </div>
      <div className='sidebar_menu'>
      { links.map((link) => (     
            <div className={'sidebar_link' + (activeLink == link.id ? ' active_class_link' : '')} onClick={(e) => setActiveLink(link.id)}>
                <i className={link.faClass}></i>
                <Link to={link.url}>{link.title}</Link>
            </div>
      ))}
      </div>
    </div>
  );
};

export default Sidebar;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a personalized React date selection tool using TypeScript

After following the instructions in the documentation for creating a custom datepicker, I finally managed to build one. However, I encountered an error stating "Function components cannot be given refs. Attempts to access this ref will fail. Did you mean ...

Encountering an internal server error while submitting a Node.js form: stream is not readable

I've encountered an issue while working on a project that involves form submission (Registration and Login). My server is functioning properly and connected to my MongoDB, everything else is working fine, but when trying to submit the form input, an e ...

As I tried running both `npm install --force` and `npm i`, an unexpected error occurred

npm WARN using --force Recommended protections disabled. npm WARN ERESOLVE overriding peer dependency npm WARN While resolving: @material-ui/[email protected] npm WARN Found: [email protected] npm WARN node_modules/react npm WARN react@"^18.2.0" fro ...

Changing the key name for each element in an array using ng-repeat: a guide

In my current project, I have an array of objects that I am displaying in a table using the ng-repeat directive. <table> <thead> <tr> <th ng-repeat="col in columnHeaders">{{col}}</th> //['Name&apo ...

Error encountered: Attempting to use a class as a function in vue-socket.io is not permitted

I am developing a Vue chrome extension where I am attempting to implement web sockets using vue-socket.io. I have followed the basic instructions on deploying a node server with express and socket.io on Heroku, but I am encountering issues with the conne ...

Understanding the concept of hoisting in JavaScript for global variables and functions

I've been curious about hoisting. I understand that if a global function shares the same name as a global variable, the function will overwrite the variable's name. Is this correct? Here is an example code snippet. (function() { console.log ...

What is the best way to send a form using jQuery's AJAX function?

Essentially, I have a form that contains several text boxes along with a submit button. The issue I am facing is that upon submitting the form, only the value of the username box is being sent and not the values of the other text boxes. I am using a servl ...

The attempt to bring in the model using `require` has resulted in an error. The `require` method used here, in combination with `path.join`, does

As a beginner in web development, I have been working on a project using MySQL, Node.js with Express. However, I am encountering a TypeError issue when using Sequelize. Can anyone kindly explain this to me and assist me in finding a solution? "seque ...

Having trouble with jQuery's find() function not working in conjunction with prev()?

I'm in need of some assistance because I think I may be approaching this the wrong way. Here is a link to the jsfiddle I have created: https://jsfiddle.net/m35o8jjL/2/ Below is the HTML code snippet: $( ".layered_subtitle_heading" ).click(function ...

In React and Next.js, the function setState is unavailable

Welcome Page "use client"; import { useState, useEffect } from "react"; import Loading from "./loading"; import Link from "next/link"; import Courses from "./components/courses"; export default function We ...

What could be causing the Contact anchor element to not function properly?

I've been working on creating a dropdown menu for my API, but I'm having trouble getting the anchor links to function properly. I even attempted changing the "a" element to an onclick call with javascript:void(0) and added a function to open Gmai ...

Experiencing Excessive Recursion While Dynamically Attaching Click Event Listener With Post Method to a Div Element

I'm encountering 'too much recursion' errors when trying to dynamically add a click handler to specific div tags with the class name 'reportLink'. Despite successfully logging the innerText of the divs, the code fails when attempti ...

What is the process for choosing all items and then canceling the selection in a

I utilized the information on this webpage to generate the following code snippet: https://getbootstrap.com/docs/5.0/forms/checks-radios/#indeterminate Upon clicking the checkbox with the ID of (flexCheckIndeterminate), all checkboxes located below it wil ...

Using JQuery to visually enhance the menu selection by displaying an image and altering the background color upon hovering

Hello fellow JQuery/Javascript beginners! I recently put together a menu and wanted to add some interactive elements. Specifically, I want the background color to change when a user hovers over an item (simple enough with CSS), but I also want to include a ...

CSS Background Color Not Displaying Correctly

My HTML5 page has an issue where the image is taking over the background color of the entire page. I want to adjust it so that the image appears in the background, while the background color shows up behind the content on top. Check out my code below and l ...

Styled-Component: Incorporating Variables into Styled-Component is my goal

Currently, I am working on an app and have created a separate file for styling. I decided to use style-components for custom CSS, but faced an issue where I couldn't access variables instead of HEX values. Even after storing color values in a variable ...

I am encountering an issue where the nested loop in Angular TypeScript is failing to return

I am facing an issue with my nested loop inside a function. The problem is that it is only returning the default value of false, instead of the value calculated within the loop. Can someone please point out what I might be doing incorrectly? Provided belo ...

How can I restrict the highest possible date selection in reactjs?

I am working on a project that requires users to select dates using datetime-local, but I want to limit the selection to only three months ahead of the current date. Unfortunately, my current implementation is not working as expected. Any assistance woul ...

What is the best way to determine the correct version of Material UI to incorporate into my React application?

On the React starter kit I'm using, I have react and react-dom 15.4.2 installed. I've been attempting to install material-ui but npm is informing me that the latest version requires a higher version of React (16.0). Is there a way for me to inst ...

Ways to populate an AngularJS array with text input from HTML

I'm new to AngularJS - attempting to create a simple todo-list application. I'm struggling with how to insert the text value from the input box into the 'todos' array. Here's my code snippet. HTML: <body ng-controller="MainCt ...