Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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} />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading