Usurper
Usurper

Reputation: 97

How to add active class on link click

I have a Sidebar component, I want to add the active_class_link style to the DIV on onClick() event. I have setup the whole function, but I don't know how to do this for every DIV i have.

I want to work it like when I click on one link than from any other active div, active_class_link style should be removed and added to the clicked link.

My Sidebar component is as follows,

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>

        <div className='sidebar_link ' onClick={(e) => handleActive(e)}>
          <i className='fas fa-user-circle'></i>
          <Link to='/profile'>Profile </Link>
        </div>
        <div className='sidebar_link ' onClick={(e) => handleActive(e)}>
          <i className='fas fa-book'></i>
          <Link to='/subjects'>Subjects </Link>
        </div>
        <div className='sidebar_link ' onClick={(e) => handleActive(e)}>
          <i className='fa fa-graduation-cap'></i>
          <Link to='/courses'>Courses</Link>
        </div>
        <div className='sidebar_link ' onClick={(e) => handleActive(e)}>
          <i className='fas fa-book-open'></i>
          <Link to='/notes'>Notes</Link>
        </div>
        <div className='sidebar_link ' onClick={(e) => handleActive(e)}>
          <i className='fas fa-chalkboard-teacher'></i>
          <Link to='/class'>Online Class</Link>
        </div>
        <div className='sidebar_link ' onClick={(e) => handleActive(e)}>
          <i className='fa fa-handshake-o'></i>
          <Link to='/contact'>Contact Developer</Link>
        </div>
        <h2>LEAVE</h2>
        <div className='sidebar_logout'>
          <i className='fa fa-power-off'></i>
          <Link to='/' onClick={handleLogout}>
            Log out
          </Link>
        </div>
        <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>

My Active Class Link styles is as follows,

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

Any possible solution than please help.

Upvotes: 0

Views: 1082

Answers (2)

t0mgerman
t0mgerman

Reputation: 184

Edit: Check Sean's answer below re: <NavLink/> elements. I missed that you could have used that component. If you want to do anything manual, then I would stand by my answer, but I think Sean's answer will serve you best...

If you make your .sidebar-menu items a result of data, you will be able to toggle the active state more easily. You should be able to do something like:

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;

Upvotes: 0

Sean
Sean

Reputation: 975

If you change all of your Links to NavLinks then you can add an active class automatically.

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

Upvotes: 1

Related Questions