Home > front end >  Need a active class on first div
Need a active class on first div

Time:11-23

I'm trying to add an active class on the map element with hover. Everything is perfect but I need to add an active class on the first div when I do not hover over any.

Here is my code...

{WhatWeOfferData.map(({ img, title, para}, index) => {
        return (
          <div
              className={`${style.card} ${addActive.index === index && addActive.show ? `${style.active}` : ""}`}
              onm ouseEnter={hoverOn}
              onm ouseLeave={hoverOff}
              key={index}
              data-id={index}
          >
            <Image src={img} alt="offer_images" width={37} height={41} />
            <h2>{title}</h2>
            <p>{para}</p>
          </div>
        );
      })}

and

  let [addActive, setAddActive] = useState(false);
const hoverOn = (e) => {
    setAddActive({
      index: parseInt(e.currentTarget.dataset.id),
      show: true
    });
  };
  const hoverOff = (e) => {
    setAddActive({
      index: parseInt(e.currentTarget.dataset.id),
      show: false
    });
  };

CodePudding user response:

Simply do this:

{
  WhatWeOfferData.map(({ img, title, para}, index) => {
    return (
      <div className={`${style.card} ${addActive.index === index && addActive.show ? `${style.active}` : index === 0 && !addActive.show ? `${style.active}` : ""}`}
          onm ouseEnter={hoverOn}
          onm ouseLeave={hoverOff}
          key={index}
          data-id={index}
      >
          <Image src={img} alt="offer_images" width={37} height={41} />
          <h2>{title}</h2>
          <p>{para}</p>
      </div>
    );
})}

CodePudding user response:

if index is zero and state is not showing anything, return the active class

className={`${style.card} ${getClass(index)}`}


const getClass = (index) => {
    if(addActive.index === index && addActive.show )
       return style.active

    if(index === 0){
       if(!addActive.show) return style.active
    }

    return ""
}
  • Related