Warm tip: This article is reproduced from stackoverflow.com, please click
javascript react-hooks reactjs

use React Hooks to change the elements class Name and siblings

发布于 2020-06-02 16:44:09

I have this function component in react hooks. and need when I click in any element in the list to change className to 'active' and remove the className from the other elements

const SideBar = () =>{
  const [activeClass, setClass] = useState('');

  return (
    <div className="sidebar">
      <ul>
        <li> <Link onClick={() => setClass('active')} className={activeClass} to="/"> Home </Link> </li>
        <li> <Link to="/about"> About </Link> </li>
        <li> <Link to="/form"> Form </Link> </li>
      </ul>
    </div>
  )
}
Questioner
Mohammed Alngaawy
Viewed
268
Zohaib Ijaz 2020-03-19 20:46

I hope you must be using react-router-dom so you can use rect-router-dom api to determine the active item

import {
  useLocation
} from "react-router-dom";

const SideBar = () =>{
  const [activeClass, setClass] = useState('');
  let { pathname } = useLocation();

  return (
    <div className="sidebar">
      <ul>
        <li> <Link className={pathname === '/' ? 'active' : ''} to="/"> Home </Link> </li>
        <li> <Link to="/about" className={pathname === '/about' ? 'active' : ''}> About </Link> </li>
        <li> <Link to="/form" className={pathname === '/form' ? 'active' : ''}> Form </Link> </li>
      </ul>
    </div>
  )
}

import { NavLink } from 'react-router-dom';

const SideBar = () => {
      const isActive = path => (match, location) => {
        if (!match) {
          return false;
        }
        return match.url === path;
      };

      return (
        <div className="sidebar">
          <ul>
            <li> <NavLink isActive={isActive('/')} activeClassName="active" to="/"> Home </NavLink> </li>
            <li> <NavLink to="/about" isActive={isActive('/about')} activeClassName="active"> About </NavLink> </li>
            <li> <NavLink to="/form" isActive={isActive('/form')} activeClassName="active" > Form </NavLink> </li>
          </ul>
        </div>
      )
    }