Home > Blockchain >  Reactjs onClick toggle on off
Reactjs onClick toggle on off

Time:10-26

i am trying to write code using useState to toggle between on and off when clicking on button.


const [isON, setIsON] = React.useState(true)
<button onClick={() => setIsON(!isON)}>{ isON ? console.log('ON') : console.log('off') } />

i used this website's code, but when i use this in react i get syntax error

CodePudding user response:

You are probably getting a syntax error both because you are calling functions where template should be AND because some HTML elements (such as <button>), can't be self-closing.
So <button /> is not allowed, but if we REALLY want it to be empty,
we can do <button></button>.

But back to the main point,
React expects the returned value from your template tags to be either string \ number \ null or anything else that React considers a valid child.

The return value of a console.log is void, which isn't considered a valid React child.

In other words, you can't call console.log from within a tag in the template.
But if you really want it in your template, you can do this:

<button onClick={() => setIsON(!isON)}>Click me!</button>
{ isON ? console.log('ON') : console.log('off') }

Or better yet, use the ternary operator inside of the log function:

<button onClick={() => setIsON(!isON)}>Click me!</button>
{ console.log(isON ? 'ON' : 'off') }

Or even better yet, move it outside of the template as it has no business being there in the first place.
Since a React component re-renders whenever there is a change in state, the console.log can simply be put anywhere in the component instead.

function MyComp() {
   const [isON, setIsON] = React.useState(true)

   console.log(isON ? 'ON' : 'off')

   return (
      ...
      <button onClick={() => setIsON(!isON)}>Click me!</button>
      ...
   )
}

CodePudding user response:

Could probably do with more code, but if that is the code you have written, you need to close the button tag correctly. If you have text in between, you have to have the element <button>{TEXT}</button>

<button onClick={() => setIsON(!isON)}>{ isON ? console.log('ON') : console.log('off') } />

Needs changing to

<button onClick={() => setIsON(!isON)}>{ isON ? console.log('ON') : console.log('off') }</button>
  • Related