Home > OS >  Ternary operation not working on button click in reactJS?
Ternary operation not working on button click in reactJS?

Time:11-01

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.

CodePudding user response:

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>)
}
</>
)

CodePudding user response:

You've forgotten to wrap your whole JSX elements in a parent element while using the ternary operator.

So, wrap them in a fragment <></> element or React.Fragment

return (
  <>
    {
      // your ternary logics here
    }
  </>
)

Or:

import React, {Fragment} from 'react';

// rest of the codes ...

return (
  <Fragment>
    {
      // your ternary logics here
    }
  </Fragment>
)
  • Related