Home > Net >  Render className with ternary nested If Els statement React
Render className with ternary nested If Els statement React

Time:10-12

I do have a small issue I do need to render a className based on few conditions. I have a Play button, Live button and general buttons. Most classes are the same, but I do need to add extra class to a play button.

My code so far is looking like this:

 className={`"Controller-Button player-btn icon" ${
          isSelected
            ? `${btnName === "PLAYER_LIVE" ? " live-button" : ""}`
            : `${btnName === "PLAYER_LIVE" ? " live-button" : ""}`
        }`}

And now I am stuck. I need to add extra condition before isSelecetd: btnName === "PLAYER_PLAY" ? " play-button" : "" but i do have issue how properly put this in such render. If I will add btnName === "PLAYER_LIVE" ? " live-button" : "play-button" this class wil be in all buttons.

CodePudding user response:

You can use something like that:

const classes = ["Controller-Button", "player-btn", "icon"];
if(isSelected) {
  classes.push("live-button")
} else if(somethingCondition) {
   classes.push("someClass")
}

etc...

 className={classes.join(' ')}

CodePudding user response:

I would suggest to move this logic into a function. Something like

const getClassName = () => {
  let className
  if (btnName === 'PLAYER_PLAY') {
    // applicable logic here for className here
  } else {
    // applicable logic here for className here
  }
  return className
}
  • Related