Home > Blockchain >  How can I get the value of a Toggle JSX Component?
How can I get the value of a Toggle JSX Component?

Time:10-26

I have this

function Toggle(){

    const [toggleOn, setToggleOn] = useState(false);

    return (
        <div>
            {toggleOn == true && <Settingson className={classes.settingson} onClick={() => setToggleOn(d => !d)} value="true" name="toggle"/>}
            {toggleOn == false && <Settingsoff className={classes.settingsoff} onClick={() => setToggleOn(d => !d)} value="false" name="toggle"/>}
        </div>
    )
}

export default Toggle;

And somehow I want to get the value of this

<Toggle />

I tried many things, but couldn't came up with a solution. Please help! I am new to React Next Js.

I tried to get the value of a jsx component, but It doesn't work. Somehow I need to check if the value of the toggle is true or not.

CodePudding user response:

Your component needs to be authored so that it can inform its consuming component that its state has changed: see it as a way data is "emitted" from a child component.

In the example below, I have updated your component so that it accepts a onInput prop, which should be a method. It is invoked whenever the click event is fired, and "piggy-backs" on the state change to toggleOn:

function Toggle({ onInput }){
    const [toggleOn, setToggleOn] = useState(false);
    const onToggleClick = (value) => {
      // Updates internal state
      setToggleOn(value);

      // Fires the callback passed as a prop
      onInput(value);
    };

    return (
        <div>
            {toggleOn == true && <Settingson className={classes.settingson} onClick={() => onToggleClick(d => !d)} value="true" name="toggle"/>}
            {toggleOn == false && <Settingsoff className={classes.settingsoff} onClick={() => onToggleClick(d => !d)} value="false" name="toggle"/>}
        </div>
    )
}

export default Toggle;

Then in the parent component it is a matter of passing in a function to the prop, e.g.:

const onToggleInput = (value) => console.log(value);

return <Toggle onInput={onToggleInput} />

CodePudding user response:

Not sure if I get what you are trying to do but I think you can simplify in a similar way

function Toggle(){

    const [toggleOn, setToggleOn] = React.useState(false);
    
    const handleToggle = () => {
        console.log("toggleOn",toggleOn)
        setToggleOn(prev => !prev)
    }

    return (
        <div>
            <button onClick={handleToggle} value={toggleOn} name="toggle">something</button>
        </div>
    )
}

just replace the button with your component Settings, you just need one that handles true/false values or add a conditional ternary operator for conditional rendering.

return toggleOn ? <TrueComponent /> : <FalseComponent />
  • Related