Pass a hook and a function to a function

Hello everyone.

Given the main component called Registro, which has 2 components in IonContent: RegistroNuevaCuenta and IonAlert

What I need is to pass the hook showAlert to RegistroNuevaCuenta So that this is the one who shows the IonAlert. Is this possible?

const Registro: React.FC = () => {
  const [showAlert, setShowAlert] = useState(false);

  return (
    <IonPage>
      <IonHeader>
      <IonToolbar>
        <IonGrid>
          <IonRow>
          <IonCol size="1"><a href={"/home"}><IonIcon icon={arrowBack}  id="flecha-volver">  </IonIcon></a></IonCol>
          <IonCol id="columna2" ><strong id="texto-pagina">Registro</strong></IonCol>
          </IonRow>
        </IonGrid>
      </IonToolbar>
      </IonHeader>
      <IonContent fullscreen>
        <RegistroNuevaCuenta></RegistroNuevaCuenta>
        
        <IonAlert
          isOpen={showAlert}
          onDidDismiss={() => setShowAlert(false)}
          cssClass='my-custom-class'
          header={'Alert'}
          subHeader={'Subtitle'}
          message={'This is an alert message.'}
          buttons={['OK']}
        />
      </IonContent>
    </IonPage>
  );
};
const RegistroNuevaCuenta = () => {
  const [tipo, setCount] = useState(0)
  const [user, setUser] = useState(0)
  const [email, setEmail] = useState(0)
  const [password, setPassword] = useState(0)

  const [codigo, setCodigo] = useState(0)
  const [codigo_agregado, setCodigo_agregado] = useState(1)

  /*
more code that doesn't matter
*/
}

Its posible to use useBetween?

You want to pass a callback function as a prop to your RegistroNeuvaCuenta component.

const RegistroNuevaCuenta: React.FC<{ onShowAlert: () => any}> = ({onShowAlert}) => {
  const [tipo, setCount] = useState(0)
  const [user, setUser] = useState(0)
  const [email, setEmail] = useState(0)
  const [password, setPassword] = useState(0)

  const [codigo, setCodigo] = useState(0)
  const [codigo_agregado, setCodigo_agregado] = useState(1)

// Where you need to invoke an alert use:

onShowAlert();

  /*
more code that doesn't matter
*/
}

And then use it like:

<RegistroNuevaCuenta onShowAlert={() => setShowAlert(true)}></RegistroNuevaCuenta>

1 Like

Or import alertController from ‘@ionic/core’ and just use it in the code:

 alertController.create({ message: 'My alert message', buttons: ['Ok'] }).then(alert => alert.present());

I use this a lot rather than polluting the JSX with IonAlert.

1 Like