Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Apply style onMouseEnter on mapped element

I want to apply a custom style when I hover a div.
I have a .map() function that will create a card for each element in the datas received.

To achieve that :

  • I map my datas and give them a unique index as key
  • I use onMouseEnter and onMouseLeave to add and remove my class

I know I could use :hover in CSS, but as a React / Tailwind project, I try to write as less css as I can, and I want to learn by trying new stuff.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Problem
When I hover my card, the current card and all the next ones until the last one take that class. not only the hovered one.

I don’t understand why it takes all last card after hovered one.

Where is my mistake ?

Here is what I tried

const addCustomShadow = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
    const card = e.currentTarget;
    card.classList.add("custom-box-shadow");
};

const removeCustomShadow = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
    const card = e.currentTarget;
    card.classList.remove("custom-box-shadow");
};

{data.map((project, index) => {
   return (
      <div
          key={index}
          onMouseEnter={addCustomShadow}
          onMouseLeave={removeCustomShadow}
          className='rounded-lg bg-white p-6 shadow-xl transition-all duration-150'>
             [...]
      </div>
    );
})}

>Solution :

create a useState variable and maintain the state for each item in the map

const [showClass, setShowClass] = useState({})
const addCustomShadow = (id: number) => {
    setShowClass(state => ({
          ...state,
         [id] : true
    }))
};

const removeCustomShadow = (id: number) => {
    setShowClass(state => ({
          ...state,
         [id] : false
    }))
};

{data.map((project, index) => {
   return (
      <div
          key={index}
          onMouseEnter={() => addCustomShadow(project.id)}
          onMouseLeave={() => removeCustomShadow(project.id)}
          className={`rounded-lg bg-white p-6 shadow-xl transition-all duration-150 ${showClass[project.id]? 'custom-box-shadow': ''}`}>
             [...]
      </div>
    );
})}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading