DEV Community

Cover image for Build React Native Fitness App #6 : Firebase Email Authentication ,integrate Formik and Yup
0xAirdropfarmer
0xAirdropfarmer

Posted on • Originally published at kriss.io on

Build React Native Fitness App #6 : Firebase Email Authentication ,integrate Formik and Yup

this tutorial is fourth chapter of series build fitness tracker this app use for track workouts, diets, or health activities and analyze data and display suggestion the ultimate goal is to create food and health recommendation using Machine learning we start with creating app that user wants to use and connect to google health and apple heath for gathering everything to create dataset that uses for train model later I start with ultimate goal but we will start with create react native app and set up screen navigation with React navigation. inspired by React native Theme from instamobile

after we complete coding from UI part now we can implement authentication using Firebase, but before we going to Firebase part we want to add input validation with Formik and Yup for two packages is a popular form management package for both React and React Native

install Formik and Yup

yarn add formik yup

then import to file that we want to use

import {Formik} from 'formik';
import \* as yup from 'yup';

using on the register form

for Formik we need to wrap our old form with Formik instance like here

<Formik
           initialValues={{email: ''}}
           onSubmit={values => {
             alert(JSON.stringify(values));
           }}>
           {formikProps => (
             <React.Fragment>
               <View style={styles.headerContainer}>
                 <Icon
                   name="md-fitness"
                   size={80}
                   type="ionicon"
                   color={'#7265E2'}
                 />
                 <Text h4 style={{textAlign: 'center'}}>
                   What is your E-mail address?
                 </Text>
               </View>
               <Input
                 leftIcon={
                   <Icon
                     name="mail-outline"
                     color="rgba(110, 120, 170, 1)"
                     size={25}
                   />
                 }
                 placeholder="enter your Email"
                 inputContainerStyle={{
                   borderWidth: 1,
                   borderColor: 'white',
                   borderLeftWidth: 0,
                   height: 50,
                   backgroundColor: 'white',
                   marginBottom: 20,
                 }}
                 placeholderTextColor="grey"
                 autoCapitalize="none"
                 autoCorrect={false}
                 keyboardType="email-address"
                 returnKeyType="next"
                 onChangeText={formikProps.handleChange('email')}
               />
               <View style={styles.btnWrapper}>
                 <Button
                   title="Continue"
                   loading={false}
                   loadingProps={{size: 'small', color: 'white'}}
                   buttonStyle={{
                     backgroundColor: '#7265E3',
                     borderRadius: 15,
                   }}
                   titleStyle={{fontWeight: 'bold', fontSize: 23}}
                   containerStyle={{
                     marginVertical: 10,
                     height: 50,
                     width: 300,
                   }}
                   onPress={formikProps.handleSubmit}
                   underlayColor="transparent"
                 />
               </View>
             </React.Fragment>
           )}

for a highlight, first, we define initial value for a form then add function for handle form submit event we inject Formik props for getting form data and intercept event on a form

here initial result from iPhone

And from Android

next step we setup input validation with Yup

first, create new yup instance and define a validation rule

const SignupSchema = Yup.object().shape({
  email: Yup.string()
    .email('Invalid email')
    .required('Email is Required'),
});

next, attach to Forkmik

<Formik
  initialValues={{email: ''}}
  onSubmit={values => {
    alert(JSON.stringify(values));
  }}
  validationSchema={SignupSchema}>

then disable button before input valid will enable

<Button
    disabled={!(formikProps.isValid && formikProps.dirty)}

finally with display validation message below email input

{formikProps.errors.email ? (
   <Text style={{color: 'red'}}>{formikProps.errors.email}</Text>
 ) : null}

now your can see the result

adding to register and password screen

now we can pass email to the input password screen

<Formik
   initialValues={{email: ''}}
   onSubmit={values => {
     this.props.navigation.navigate('PasswordInputScreen',{email: values.email});
   }}

next, we can implement validation in the Input password screen

first import three package

import firebase from 'react-native-firebase';
import {Formik} from 'formik';
import \* as Yup from 'yup';

start define input validation with Yup

const SignupSchema = Yup.object({
  password: Yup.string()
    .required('Password is required')
    .min(6, 'Password must be at least 6 characters'),
  passwordConfirm: Yup.string()
    .oneOf([Yup.ref('password'), null], 'Passwords must match')
    .required('Password confirm is required'),
});

for Formik code we can copy from email input screen

<Formik
  initialValues={{password: '', passwordConfirm: ''}}
  onSubmit={(values, {setSubmitting}) => {
    this.signUp(values, this.props.navigation);
    setSubmitting(false);
  }}
  validationSchema={SignupSchema}>

and update initial form also add a function that uses for the handle registration function

then add Formik props to input

<Input
        leftIcon={
          <Icon
            name="lock"
            color="rgba(110, 120, 170, 1)"
            size={25}
          />
        }
        placeholder="Email"
        inputContainerStyle={{
          borderWidth: 1,
          borderColor: 'white',
          borderLeftWidth: 0,
          height: 50,
          backgroundColor: 'white',
          marginBottom: 20,
        }}
        autoCapitalize="none"
        placeholder="Enter your Password"
        secureTextEntry={true}
        autoCorrect={false}
        returnKeyType="next"
        onChangeText={formikProps.handleChange('password')}
      />
      <Input
        leftIcon={
          <Icon
            name="lock"
            color="rgba(110, 120, 170, 1)"
            size={25}
          />
        }
        placeholder="Confirm Password"
        inputContainerStyle={{
          borderWidth: 1,
          borderColor: 'white',
          borderLeftWidth: 0,
          height: 50,
          backgroundColor: 'white',
          marginBottom: 20,
        }}
        autoCapitalize="none"
        secureTextEntry={true}
        autoCorrect={false}
        returnKeyType="next"
        onChangeText={formikProps.handleChange('passwordConfirm')}
      />
      {formikProps.errors.password ? (
        <Text style={{color: 'red'}}>
          {formikProps.errors.password}
        </Text>
      ) : null}
      {formikProps.errors.passwordConfirm ? (
        <Text style={{color: 'red'}}>
          {formikProps.errors.passwordConfirm}
        </Text>
      ) : null}
      <BoxPasswordStrengthDisplay
        password={formikProps.values.password}
      />

also password strength component we getting password value when onChange value fired

here some result we disabled submit button until input validation correct

Register to Firebase

next step we activated the firebase sign-in method

now we can use email login with firebase

signUp = (values, navigation) => {
   this.setState({loading: true});
   let email = this.props.navigation.getParam('email');
   firebase
     .auth()
     .createUserWithEmailAndPassword(email, values.password)
     .then(user => {
       this.setState({user});
       alert('Registration success');
     })
 };

here simple register function with Firebase we receive an email from props and password from Formik then when register success we send an alert

and your will see new row on Firebase

conclusion

in this chapter, we learn how to use Formik and Yup also Firebase email register next chapter we repeat the process again in the login screen

Originally published at [_Kriss](https://kriss.io/build-react-native-fitness-app-6-firebase-email-authentication-integrate-formik-and-yup/)._


Top comments (0)