React , when you add class remove other ones

35 Views Asked by At

I got a total of 3 conditions. When I add the class possible-links-cont-star-btn with the x.feature condition I want to remove the all other classes element have.

<Link
  key={i}
  onClick={() => setSelectedEvent(x)}
  className="possible-links-cont-link"
>
  <button
    className={` 
      ${(i === 0 || i === izmirEventItemData.length - 1) ? "possible-links-cont-empty-btn" : "possible-links-cont-btn"}
      ${isHovered ? "active" : ""}
      ${x.feature ? "possible-links-cont-star-btn" : ""}        
    `}
    onMouseOver={() => {
      setHoveredText(x);
      setIsHovered(true);
    }}
    onMouseLeave={() => setIsHovered(false)}
  ></button>
</Link>

I tried to do that without conditional rendering but couldn't do it.

1

There are 1 best solutions below

0
Yuu On

in order to achieve this, you need to split this in two different things, the group that is going to be joined and the class that needs to be alone

And also if the you are using string templates be careful with the break lines because string templates save the new lines in the string resulting in an unexpected behavior

let buttonClass =
  i === 0 || i === izmirEventItemData.length - 1
    ? "possible-links-cont-empty-btn"
    : "possible-links-cont-btn";
buttonClass += isHovered ? " active" : "";
if (x.feature) {
  buttonClass = "possible-links-cont-star-btn";
}

<Link
  key={i}
  onClick={() => setSelectedEvent(x)}
  className="possible-links-cont-link"
>
  <button
    className={buttonClass}
    onMouseOver={() => {
      setHoveredText(x);
      setIsHovered(true);
    }}
    onMouseLeave={() => setIsHovered(false)}
  >
    {" "}
  </button>
</Link>;

PD: the final result that you expect is not very clear in your question but with this code you can adapt it to your needs, it is the starting point of your desired answer