-2

Can someone please explain the code to me? I am not able to understand why the code says !toggle inside onClick and ? inside return In short the code is confusing to me as I am a beginner.

Ant help will be much appreciated.

import {useState} from 'react';

const Toggle = ({children}) => {
    const [toggle,setToggle] = useState(true);
    return (
        <div onClick={() => setToggle(!toggle)}>
            {toggle ? children: ""}
        </div>
    )
}

export default Toggle
zero298
  • 25,467
  • 10
  • 75
  • 100
  • "!" means "not" or opposite of current value and the "?" Is part of the ternary expression. See https://stackoverflow.com/a/9550412 – zero298 May 30 '21 at 19:27
  • Does this answer your question? [What does this symbol mean in JavaScript?](https://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript) – zero298 May 30 '21 at 19:29

1 Answers1

2

"!" is a negation. It returns the opposite boolean value of what was given to it (for example, if toggle is false, it will return true). This means that the toggle is set to the inverse of what it was.

"?" is the ternary operator. If the variable is true, it will choose the first value (i.e. children). If not, it will choose the value behind the ":", i.e. an empty string.

fynsta
  • 348
  • 3
  • 10