Search code examples
cssreactjsconditional-operatorconditional-renderingreact-css-modules

How do I use ternary operator for classnames with css modules?


I am facing some difficulty effecting a styling with the ternary operator in an element's className.

I created three buttons to render to a particular component when any of them are clicked, and I also intend to use a background color change on the buttons when each component assigned to it is rendered to denote which button was clicked.

The issue I face is that while the components are successfully rendering, the background color for the button doesn't change.

<div className="App">
      <div className ="App-btns">
        <button onClick = {fPro} className = {`${styles[{pro ? "active" : null}]}`}>Profile</button>
        <button onClick = {fSec} className = {`${styles[{sec ? "active" : null}]}`}>Security</button>
        <button onClick = {fVer} className = {`${styles[{ver ? "active" : null}]}`}>Verification</button>
      </div>
      <div className = "App-render">
        {pro && <Profile/>}
        {sec && <Security/>}
        {ver && <Verification/>}
      </div>
    </div>

I created three variables; pro, sec and ver. I set all to false except pro which was set to true, which renders the component, Profile as the default. Then, I created three functions also, which sets its corresponding variables to true and others to false and they are activated when a button Is clicked.

I also used the variables in the ternary operator to assign a classname, when a particular variable is true. The class name should be set to active and a corresponding styling change should come with it, but this doesn't seem to work.

.active{
  background-color: purple;
  border: 1px solid purple;
}

Solution

  • <div className="App">
      <div className ="App-btns">
        <button onClick = {fPro} className = {`${pro ? styles.active : null}`}>Profile</button>
        <button onClick = {fSec} className = {`${sec ? styles.active : null}`}>Security</button>
        <button onClick = {fVer} className = {`${ver ? styles.active : null}`}>Verification</button>
      </div>
      <div className = "App-render">
        {pro && <Profile/>}
        {sec && <Security/>}
        {ver && <Verification/>}
      </div>
    </div>