Home > Blockchain >  Apply style onMouseEnter on mapped element
Apply style onMouseEnter on mapped element

Time:12-12

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.

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}
          onm ouseEnter={addCustomShadow}
          onm ouseLeave={removeCustomShadow}
          className='rounded-lg bg-white p-6 shadow-xl transition-all duration-150'>
             [...]
      </div>
    );
})}

CodePudding user response:

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}
          onm ouseEnter={() => addCustomShadow(project.id)}
          onm ouseLeave={() => removeCustomShadow(project.id)}
          className={`rounded-lg bg-white p-6 shadow-xl transition-all duration-150 ${showClass[project.id]? 'custom-box-shadow': ''}`}>
             [...]
      </div>
    );
})}
  • Related