noobcode0000
noobcode0000

Reputation: 243

Ternary operation not working on button click in reactJS?

I am conditionally rendering a button so when it is clicked, the button changes from a play to pause. I am doing this via ternary operation, however, when the button is clicked it does not change. Here is my code:

...
const isOn = true;
...

return(
...
{isOn ? (<Button className="icon" color="info" type="submit" onClick={startMe}><i className="playicon"/></Button>) : (<Button className="icon" color="info" type="submit" onClick={stopMe}><i className="pauseicon"/></Button>)}
...
)

I don't really understand why this isn't working. If I manually set isOn to false the button changes but if I click it does not.

Upvotes: 0

Views: 509

Answers (1)

SoGoddamnUgly
SoGoddamnUgly

Reputation: 776

You can't use regular variables like const isOn = true; because they will not cause a re-render. You need to use state.

const [isOn, setIsOn] = useState(true); // set default to false if you want

const startMe = () => {
  setIsOn(true);
}

const stopMe = () => {
  setIsOn(false);
}

return(
<>
{isOn
  ? (<Button className="icon" color="info" type="submit" onClick={startMe}><i className="playicon"/></Button>)
  : (<Button className="icon" color="info" type="submit" onClick={stopMe}><i className="pauseicon"/></Button>)
}
</>
)

Upvotes: 1

Related Questions