1

I've built a Register Page Here is Its Code:

import React, { Component } from "react";
import firebase from "../util/firebase";
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  TextInput,
  ActivityIndicator,
  Alert,
} from "react-native";
import {
  widthPercentageToDP as wp,
  heightPercentageToDP as hp,
} from "react-native-responsive-screen";
import { MaterialCommunityIcons } from "@expo/vector-icons";

export default class Register extends React.Component {
  //State Constructor
  constructor() {
    super();
    this.state = {
      confirmPassword: "",
      email: "",
      password: "",
      isLoading: false,
      buttonColor: "#8b898a",
      inputColor: "grey",
    };
  }
  //Change Button Color if Input Fieldes Are filled
  changeColorIfFilled() {
    let currentColor = this.state.buttonColor;
    if (
      this.state.email != "" &&
      this.state.password != "" &&
      this.state.confirmPassword != ""
    ) {
      currentColor = "#7356bf";
    } else currentColor = "#8b898a";
    this.setState({ buttonColor: currentColor });
  }
  //Update Input State to Current Input Value
  updateInputVal = (val, prop) => {
    const state = this.state;
    state[prop] = val;
    this.changeColorIfFilled();
  };
  //Register Function
  registerUser = () => {
    //If Input Blank Return Alert
    if (this.state.email === "" && this.state.password === "") {
      Alert.alert("Enter details to signup!");
    }
    //If Passwords Dont Match Return Alert
    else if (this.state.password !== this.state.confirmPassword) {
      Alert.alert("Passwords Don't Match");
    }
    //If Everything OK Register User
    else {
      this.setState({
        isLoading: true,
      });
      firebase
        //Activate Auth
        .auth()
        //New Function
        //Create New User
        .createUserWithEmailAndPassword(
          this.state.email,
          this.state.password
          // this.state.confirmPassword
        )
        //After Creating User
        .then(() => {
          console.log("User registered successfully!");
          this.setState({
            isLoading: false,
            email: "",
            password: "",
            // confirmPassword: "",
          });
          this.props.navigation.navigate("Next Screen");
        })
        .catch(function (error) {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          if (errorCode == "auth/weak-password") {
            alert("The password is too weak.");
          } else if (errorCode == "auth/invalid-email") {
            alert("Email is Invalid");
          } else if (errorCode == "auth/email-already-in-use") {
            alert("Email is Already in use!");
          } else {
            alert(errorMessage);
          }
          console.log(error);
        });
    }
  };

  render() {
    if (this.state.isLoading) {
      return (
        <View style={styles.preloader}>
          <ActivityIndicator size="large" color="#9E9E9E" />
        </View>
      );
    }
    return (
      <View style={styles.container}>
        <View style={styles.titleContainer}>
          <Text style={styles.title}>
            Create an account and join our studio
          </Text>
        </View>
        <View style={styles.inputsContainer}>
          <View style={styles.emailInputsContainer}>
            <TextInput
              style={styles.emailInput}
              placeholder="Email"
              value={this.state.email}
              onChangeText={(val) => this.updateInputVal(val, "email")}
            />
          </View>
          <View style={styles.passInputsContainer}>
            <MaterialCommunityIcons
              name="eye-off"
              size={24}
              color="black"
              style={styles.eyeIcon}
            />
            <TextInput
              style={styles.passwordInput}
              placeholder="Password"
              value={this.state.password}
              onChangeText={(val) => this.updateInputVal(val, "password")}
              maxLength={15}
              secureTextEntry={true}
            />
          </View>
          <View style={styles.cPassInputsContainer}>
            <TextInput
              style={styles.confirmPasswordInput}
              placeholder="ConfirmPassword"
              value={this.state.confirmPassword}
              onChangeText={(val) =>
                this.updateInputVal(val, "confirmPassword")
              }
              maxLength={15}
              secureTextEntry={true}
            />
          </View>
        </View>
        <View style={styles.buttonContainer}>
          <TouchableOpacity
            style={[
              styles.loginButton,
              { backgroundColor: this.state.buttonColor },
            ]}
            title="Continue"
            onPress={() => this.registerUser()}
          >
            <Text style={styles.loginText}>Continue</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  //Views
  container: {
    flex: 1,
    backgroundColor: "#ffffff",
  },
  titleContainer: {
    height: hp(10),
    width: wp(65.2),
    alignItems: "center",
    marginLeft: wp(17.4),
    marginRight: wp(17.4),
    marginTop: hp(17.1),
  },
  inputsContainer: {
    marginTop: hp(7.9),
    alignItems: "center",
  },
  emailInputsContainer: {
    flexDirection: "row-reverse",
  },
  passInputsContainer: {
    flexDirection: "row-reverse",
  },
  cPassInputsContainer: {
    flexDirection: "row-reverse",
  },

  buttonContainer: {
    alignItems: "center",
  },
  //Button
  loginButton: {
    flexDirection: "row",
    marginTop: hp(14),
    alignItems: "center",
    justifyContent: "center",
    borderRadius: 32.5,
    width: wp(78.3),
    height: hp(7.3),
    backgroundColor: "grey",
  },
  //Inputs
  emailInput: {
    height: hp(5.4),
    width: wp(65.2),
    borderBottomColor: "grey",
    borderBottomWidth: 1,
  },
  passwordInput: {
    height: hp(5.4),
    width: wp(65.2),
    marginTop: hp(6.3),
    borderBottomColor: "grey",
    borderBottomWidth: 1,
  },
  confirmPasswordInput: {
    height: hp(5.4),
    width: wp(65.2),
    marginTop: hp(6.3),
    borderBottomColor: "grey",
    borderBottomWidth: 1,
  },
  //Title
  title: {
    flex: 1,
    textAlign: "center",
    fontSize: hp(3.8),
  },
  //Loading
  preloader: {
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    position: "absolute",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "#fff",
  },
  //Icons
  eyeIcon: {
    position: "absolute",
    paddingTop: 45,
  },
});

Now I want to create a Custom Input component which does the following:

  • Receive a dynamic value (email/password/...)
  • Receive a dynamic Placeholder
  • Could still call my updateInputVal function on change text on the Register Module
  • if current textInput value is password then show "some Icon" inside current textInput
  • if current value inside the input is incorrect change textInput border color

How do I approached this?

3

1 Answer 1

1

First of all create Input Component.

Input.js

import React from 'react'
import { View, TextInput, StyleSheet, Text } from 'react-native' 
import { Ionicons } from '@expo/vector-icons';
const Input =  ({
    value,
    placeholder,
    onChangeText,
    onBlur,
    secureTextEntry,
    inputStyle,
    viewStyle,
    icon=false
  }) => {
    return (
      <View style={[styles.container, viewStyle]}>
        <TextInput
          style={[styles.main, inputStyle]}
          value={value}
          onChangeText={onChangeText}
          onBlur={onBlur}
          placeholder={placeholder}
          secureTextEntry={secureTextEntry}
        />
        {icon ? <Ionicons name="md-checkmark-circle" size={32} color="green" />: <View/>}
      </View>
    )
}

const styles = StyleSheet.create({
  container: {
      borderColor: 'black',
      borderWidth: 1,
      flexDirection: 'row',
      justifyContent: 'space-between'
  },
  main: {
    padding: 10
  }
})

export { Input }

Use it in Parent component

App.js

 import {Input} from './components/Input'

Simple usage

<Input placeholder={'Dynamic placeholder'}/> 

With value

<Input placeholder={'Dynamic placeholder'} value={'your value email/password'}/>

Hide text, and show icon

<Input placeholder={'Dynamic placeholder'} 
       value={'your value email/password'}
       secureTextEntry
       icon/>

I guess you got point. I used expo for icons. So if you're using React Native CLI. Use appropriate library for icons.

Sign up to request clarification or add additional context in comments.

2 Comments

where can I add field validation to check if input value is ok and change border style accordingly?
You create two styles, one for OK moments, the second one for Errors. <View style={{ borderColor: error ? erroStyle : okStyle }} />

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.