Home > Software engineering >  Passing a local value to a React class
Passing a local value to a React class

Time:12-22

I hope I was able to phrase this so as to make any sense. In any case, I'm a complete noob and can't figure out how to avoid hardcoding the optional class name inside this React button:

<button value='dogs' className={imageOptions === 'dogs' ? "options-button option-active" : "options-button"} onClick={(e) =\> handleImageOptions(e)}\>
   Dogs
</button\>

I was thinking it would be as simple as

className={imageOptions === value ? "options-button option-active"

etc

CodePudding user response:

 <button
            value="dogs"
            className={`${
              imageOptions === "dogs"
                ? "options-button option-active"
                : "options-button"
            }`}
            onClick={(e) => handleImageOptions(e)}
          >
            Dogs
          </button>

CodePudding user response:

Only add the active class based on the condition

className={`options-button ${
      imageOptions === 'dogs' ? 'option-active' : ''
    }`

CodePudding user response:

className={`options-button ${(imageOptions === 'dogs') && 'option-active'}}
  • Related