Search code examples
javascriptreactjsionic-react

How to handle changes in @ionic-react toggle item?


I'm using the @ionic-react library and now I have to add a simple IonToggle true/false value but I'm stuck, I can't handle changes and the funny thing is if I print on screen the new value I see "on" every time. How can I handle events in @ionic-react Toggle?

Code:

    import { IonToggle } from "@ionic/react";
/...
.../    
    <IonItem>
        <IonLabel color="primary" position="stacked">
            Enable Photo
        </IonLabel>
        <IonToggle datatype = "boolean" onChange={(e) => {console.log('test')}}/>
    </IonItem>

Result: enter image description here

I expect true/false value. Do you have any idea? :)


Solution

  • You can use state to manage the toggle value (true/false)

    import React, { useState } from 'react';
    
    const YourContainer: React.FC<ContainerProps> = ({ name }) => {
    
      // here you set the initial state using the useState hook:
      const [isChecked, setIsChecked] = useState(false);
      
      const buttonToggle = () => {
        setIsChecked(!isChecked);
      }
    
      return (
        <IonContent>
          <IonList>
           <IonItem>
              <IonLabel color="primary" position="stacked">
                Enable Photo
              </IonLabel>
              <IonToggle checked={isChecked} onChange={(e) => buttonToggle()}/>
            </IonItem>
          </IonList>
        </IonContent>
      )
    }