Home > Mobile >  Why isn't the "active-work" class getting added with the onClick event?
Why isn't the "active-work" class getting added with the onClick event?

Time:02-01

I'm trying to add an active class to some buttons in react but they're not applying. I'm not getting any errors or warnings and the syntax seems correct. What am i missing?

I have some handleEvent functions in JSX, I was expecting the "active-work" class to be applied to the span within the "work__filters" div. Everything else seems to be working. Code:

export default Works
part of CSS not getting applied:

import React, { useEffect, useState } from 'react'
import { projectsData } from './Data'
import { projectsNav } from './Data'
import WorkItems from './WorkItems';
import "./work.css";


const Works = () => {

  const [item, setItem] = useState({ name: 'all'});
  const [projects, setProjects] = useState([]);
  const [active, setActive] = useState(0);

  useEffect(() => {
    if(item.name === "all") {
      setProjects(projectsData);
    }
    else {
      const newProjects = projectsData.filter((project) => {
        return project.category.toLowerCase() === item.name;
      });
      setProjects(newProjects);
    }
  }, [item]);

  const handleClick = (e, index) => {
    setItem({ name: e.target.textContent.toLowerCase()});
    setActive(index);
  };

  return (
    <div>
         <div className="work__filters">
            {projectsNav.map((item, index) => {
             return (
             <span 
              onClick={(e) => {
                handleClick(e, index);
              }} 
              className={`${active === index ? 'active-work' : ""}work__item`}
              key={index}>
                {item.name}
              </span>
             );
            })}
        </div>

        <div className="work__container container grid">
            {projects.map((item) => {
                return <WorkItems item={item} key={item.id}/>
            })}
        </div>
    </div>
  );
}

export default Works

//CSS not being applied 
 .active-work {
     background-color: black;
     color: white;
  }

CodePudding user response:

The code looks fine at first glance, except you need to put a space between work__item and the condition. You should see with the Devtools that the class is getting applied, but it will probably look like , hence the styling is not applied.

https://codesandbox.io/embed/sleepy-bird-975b1m?fontsize=14&hidenavigation=1&theme=dark

<span
  onClick={(e) => {
    handleClick(e, index);
  }}
  className={`${active === index ? "active-work" : ""} work__item`}
  key={index}
>
  • Related