Search code examples
ionic-frameworkionic4ionic-react

Redirecting/Rendering different component upon validation ionic react


I'm fairly new Ionic React and trying to create an App using Ionic framework. I have a use case where I would like to redirect to another page upon a button press and validation from a function.

Here is the component I am working with

import React, { useState } from 'react';
import {
    IonContent,
    IonHeader,
    IonPage,
    IonTitle,
    IonToolbar,
    IonInput,
    IonButton,
    IonRow,
    IonCol,
    useIonViewWillEnter,
    useIonViewWillLeave,
    IonLabel
} from '@ionic/react';

import './LogIn.css'
import MainMenu from "../MainMenu";

const LogIn: React.FC<{register?: boolean; onClose?: any}> = () => {

    const [email, setEmail] = useState<string>();
    const [password, setPassword] = useState<string>();

    function handleLoginButtonPress() {
        if (validateEmail() && password !== undefined && password.trim() !== "") {
            // Network call here to check if a valid user
            console.log("valid email")
            return <MainMenu/>
        }
    }
    function validateEmail () {
        if (email !== undefined && email.trim() !== "") {
            const regexp = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return regexp.test(email);
        }
        return false;
    }

    useIonViewWillEnter(() => {
        console.log("Entering LogIn");
    });

    useIonViewWillLeave(() => {
        console.log("Exiting LogIn");
    });

    return (
        <IonPage id="loginIonPage">
            <IonHeader>
                <IonToolbar color="primary" mode="md">
                    <IonTitle class="ion-text-center">Login or Register</IonTitle>
                </IonToolbar>
            </IonHeader>

            <IonContent id="loginPage">
                <div id="loginDialog">
                    <form>
                        <IonLabel>Email</IonLabel>
                        <IonRow>
                            <IonCol id="userName">
                                <IonInput
                                    name="email"
                                    value={email}
                                    onIonChange={e => setEmail(e.detail.value!)}
                                    clearInput
                                    type="email"
                                    placeholder="Email"
                                    class="input"
                                    padding-horizontal
                                    clear-input="true"
                                    required/>
                            </IonCol>
                        </IonRow>
                        <IonLabel>Password</IonLabel>
                        <IonRow>
                            <IonCol id="password">
                                <IonInput
                                    clearInput
                                    name="password"
                                    value={password}
                                    onIonChange={e => setPassword(e.detail.value!)}
                                    type="password"
                                    placeholder="Password"
                                    class="input"
                                    padding-horizontal
                                    clear-input="true"
                                    required/>
                            </IonCol>
                        </IonRow>
                    </form>
                </div>
                <div id="buttons">
                        <IonButton
                            onClick={handleLoginButtonPress}
                            type="submit"
                            strong={true}
                            expand="full"
                            style={{ margin: 20 }}>
                            Log in
                        </IonButton>
                        <IonButton
                            routerLink="/registerUser"
                            type="submit"
                            strong={true}
                            expand="full"
                            style={{ margin: 20 }}>
                            Register
                        </IonButton>
                </div>
            </IonContent>
        </IonPage>
    );
};

export default LogIn;

How can I redirect to another page from the function handleLoginButtonPress which is invoked upon clicking on Login button. I tried reading through ionic doc but that did not help as it redirects whenever there is button click or click on an IonElement like IonLabel.


Solution

  • Use react-router-dom hooks https://reacttraining.com/react-router/web/api/Hooks/usehistory

    import { useHistory } from "react-router-dom";
    const ExampleComponent: React.FC = () => {
      const history = useHistory();
    
      const handleLoginButtonPress = () => {
        history.push("/main");
      };
    
      return <IonButton onClick={handleLoginButtonPress}>Log in</IonButton>;
    };
    export default ExampleComponent;