React native firebase login app

React native firebase login app

Posted by admin at December 25, 2019

Hi guy’s in this sort article we are going to talking about react native and firebase authentication and also we will cover how to use native base and react navigation’s as well so let’s begin with sort introductions ……..

React Native.

According to Wikipedia , React Native is an open-source mobile application framework created by Facebook. It is used to develop applications for Android, iOS, Web and UWP by enabling developers to use React along with native platform capabilities.

Firebase.

Firebase provides a realtime database and backend as a service. The service provides application developers an API that allows application data to be synchronized across clients and stored on Firebase’s cloud.

Native base.

NativeBase is a mobile application development framework which enables developers to use React Native to build native mobile applications running on the major mobile platforms – Apple iOS and Google Android. … NativeBase is targeted specially on the look and feel, and UI interplay of your app.

What we are going to build here.

Login screen
Sign Up Screen

So we know what we have to design and we have all the requirement the let’s begin by creating the react native app first.

In this article we are not going to talk about how to setup the environment for react native we assume that you have the setup.

Create your app

npm react-native init FirebaseLoginApp

cd FirebaseLoginApp

You can create your app by using expo-cli but we are using going to use react-native-cli for more info please visit official website.

Before running the app let’s install required packages in the project, go to the root directory of the project and open the terminal run the following commands.

npm install --save firebase
npm install --save native-base
npm install --save react-navigation

yarn add react-native-gesture-handler
# or with npm
# npm install --save react-native-gesture-handler

yarn add react-navigation-stack
# or with npm
# npm install --save react-navigation-stack

Now we install all the packages it’s time test our app.

Start your emulator or connect the device to test the app, we have the android and windows os so,

npm run android

Now go to https://console.firebase.google.com/ and create the your project

Open the project and create a app and copy credential for the web and inside the Authentication section enable the sign-in methods, in this article we use the email/password method

Now it’s time to open the project in the editor, you can use any editor we are going to use the VS Code it’s powerful and awesome editor and create a folder called components and create all the files that we are going to use.

First we are going to edit the App.js file

import React, {Component} from 'react';
import AppNavigation from './components/appNavigation';
import * as firebase from 'firebase';

export default class App extends Component {
  componentWillMount() {
    const firebaseConfig = {
      # your firebase credentials
    }
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
  }
  render() {
    return <AppNavigation />;
  }
}

componentWillMount is done before the INITIAL render of a component, and is used to assess props and do any extra logic based upon them (usually to also update state), and as such can be performed on the server in order to get the first server side rendered markup

Now in the AppNavigation.js file paste the following code

import {createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
import Login from './login';
import Signup from './signup';
import Profile from './profile';
const MainNavigator = createStackNavigator({
  Home: {screen: Profile},
  Login: {screen: Login},
  Signup: {screen: Signup},
});

const AppNavigation = createAppContainer(MainNavigator);

export default AppNavigation;

This file is responsible for routing and rendering between screens

Now create the login screen and paste the following code

import React, {Component} from 'react';
import {
  Container,
  Content,
  Footer,
  FooterTab,
  Button,
  Text,
  Input,
  Item,
  Right,
} from 'native-base';
import * as firebase from 'firebase';

import {StyleSheet} from 'react-native';
export default class Login extends Component {
  static navigationOptions = {
    title: 'Login Page',
    headerLeft: null,
    headerStyle: {
      backgroundColor: '#3f51b5',
    },
    headerTintColor: '#fff',
    headerTitleStyle: {
      fontWeight: 'bold',
    },
  };

  constructor(props) {
    super(props);
    this.state = {
      email: '',
      password: '',
    };
  }
  handleLogin = (email, password) => {
    firebase
      .auth()
      .signInWithEmailAndPassword(email, password)
      .then(() => this.props.navigation.navigate('Home'))
      .catch(error => this.setState({errorMessage: error.message}));
  };
  render() {
    return (
      <Container>
        <Content style={styles.login}>
          <Item rounded style={styles.textInput}>
            <Input
              placeholder="Email"
              autoCorrect={false}
              autoCapitalize="none"
              onChangeText={email => this.setState({email})}
            />
          </Item>
          <Item rounded style={styles.textInput}>
            <Input
              placeholder="Password"
              secureTextEntry={true}
              autoCorrect={false}
              onChangeText={password => this.setState({password})}
              autoCapitalize="none"
            />
          </Item>
          <Button
            full
            rounded
            onPress={() =>
              this.handleLogin(this.state.email, this.state.password)
            }>
            <Text style={styles.text}>Login</Text>
          </Button>
          <Right>
            <Text
              style={styles.texts}
              onPress={() => this.props.navigation.navigate('Signup')}>
              Don't have a account click me
            </Text>
          </Right>
        </Content>
        <Footer>
          <FooterTab>
            <Button full>
              <Text>Footer</Text>
            </Button>
          </FooterTab>
        </Footer>
      </Container>
    );
  }
}

const styles = StyleSheet.create({
  login: {
    padding: 20,
    flex: 1,
    marginTop: 50,
  },
  text: {
    fontSize: 20,
  },
  texts: {
    fontSize: 18,
    marginTop: 15,
    textDecorationLine: 'underline',
  },
  textInput: {
    marginBottom: 15,
    padding: 2,
  },
});

And register screen code

import React, {Component} from 'react';
import {
  Container,
  Content,
  Footer,
  FooterTab,
  Button,
  Text,
  Input,
  Item,
  Right,
} from 'native-base';

import * as firebase from 'firebase';

import {StyleSheet} from 'react-native';
export default class Signup extends Component {
  static navigationOptions = {
    title: 'Sign Up Page',
    headerLeft: null,
    headerStyle: {
      backgroundColor: '#3f51b5',
    },
    headerTintColor: '#fff',
    headerTitleStyle: {
      fontWeight: 'bold',
    },
  };

  constructor(props) {
    super(props);
    this.state = {
      email: '',
      password1: '',
      password2: '',
    };
  }

  signUpuser = (email, password1) => {
    try {
      let p1 = this.state.password1;
      let p2 = this.state.password2;
      if (p1 !== p2) {
        alert('password does not match');
        return;
      }
      if (p1.length < 6) {
        alert('Please enter atleast 6 charactor');
        return;
      }
      firebase
        .auth()
        .createUserWithEmailAndPassword(email, password1)
        .then(() => this.props.navigation.navigate('Home'));
      this.props.navigation.navigate('Profile', {email: email});
    } catch (error) {
      console.log(error.toSring);
    }
  };

  render() {
    return (
      <Container>
        <Content style={styles.login}>
          <Item rounded style={styles.textInput}>
            <Input
              placeholder="Email"
              autoCorrect={false}
              autoCapitalize="none"
              onChangeText={email => this.setState({email})}
            />
          </Item>
          <Item rounded style={styles.textInput}>
            <Input
              placeholder="Password"
              secureTextEntry={true}
              autoCorrect={false}
              onChangeText={password1 => this.setState({password1})}
              autoCapitalize="none"
            />
          </Item>
          <Item rounded style={styles.textInput}>
            <Input
              placeholder="Confirm Password"
              secureTextEntry={true}
              autoCorrect={false}
              autoCapitalize="none"
              onChangeText={password2 => this.setState({password2})}
            />
          </Item>
          <Button
            full
            rounded
            onPress={() =>
              this.signUpuser(this.state.email, this.state.password1)
            }>
            <Text style={styles.text}>Sign Up</Text>
          </Button>
          <Right>
            <Text
              style={styles.texts}
              onPress={() => this.props.navigation.navigate('Login')}>
              Already have a account click me
            </Text>
          </Right>
        </Content>
        <Footer>
          <FooterTab>
            <Button full>
              <Text>Footer</Text>
            </Button>
          </FooterTab>
        </Footer>
      </Container>
    );
  }
}

const styles = StyleSheet.create({
  login: {
    padding: 20,
    flex: 1,
    marginTop: 50,
  },
  text: {
    fontSize: 20,
  },
  texts: {
    fontSize: 18,
    marginTop: 15,
    textDecorationLine: 'underline',
  },
  textInput: {
    marginBottom: 15,
    padding: 2,
  },
});

Header screen

import React, {Component} from 'react';
import {
  Container,
  Header,
  Title,
  Button,
  Left,
  Right,
  Body,
  Icon,
} from 'native-base';
export default class HeaderNav extends Component {
  render() {
    return (
      <Container>
        <Header>
          <Left>
            <Button transparent>
              <Icon name="menu" />
            </Button>
          </Left>
          <Body>
            <Title>Header</Title>
          </Body>
          <Right />
        </Header>
      </Container>
    );
  }
}

Profile Screen

import React, {Component} from 'react';
import {
  Container,
  Content,
  Footer,
  FooterTab,
  Button,
  Text,
  Card,
  CardItem,
  Body,
} from 'native-base';
import * as firebase from 'firebase';
import {StyleSheet} from 'react-native';
export default class Signup extends Component {
  static navigationOptions = {
    title: 'Profile Page',
    headerLeft: null,
    headerStyle: {
      backgroundColor: '#3f51b5',
    },
    headerTintColor: '#fff',
    headerTitleStyle: {
      fontWeight: 'bold',
    },
  };
  constructor(props) {
    super(props);
    this.state = {currentUser: null};
  }

  componentDidMount() {
    firebase.auth().onAuthStateChanged(user => {
      this.props.navigation.navigate(user ? 'Home' : 'Login');
      this.setState({currentUser: user});
    });
  }
  signOut = () => {
    firebase
      .auth()
      .signOut()
      .then(function() {
        this.setState({currentUser: null});
        this.props.navigation.navigate('Login');
      })
      .catch(function(error) {
        console.log(error);
      });
  };
  render() {
    return (
      <Container>
        <Content style={styles.login}>
          <Card>
            <CardItem header>
              <Text style={styles.text}>Profile Page</Text>
            </CardItem>
            <CardItem>
              <Body>
                <Text style={styles.texts}>E-mail:</Text>
                <Button
                  onPress={() => this.signOut()}
                  full
                  rounded
                  style={{marginTop: 20}}>
                  <Text>Sign Out</Text>
                </Button>
              </Body>
            </CardItem>
          </Card>
        </Content>
        <Footer>
          <FooterTab>
            <Button full>
              <Text>Footer</Text>
            </Button>
          </FooterTab>
        </Footer>
      </Container>
    );
  }
}

const styles = StyleSheet.create({
  login: {
    padding: 20,
    flex: 1,
    marginTop: 15,
  },
  text: {
    fontSize: 25,
    fontWeight: 'bold',
  },
  texts: {
    fontSize: 18,
    marginTop: 15,
  },
  textInput: {
    marginBottom: 15,
    padding: 2,
  },
});


Comments

Write a Reply or Comment

Your email address will not be published. Required fields are marked *