How to authenticate users using React and Firebase

Authenticating users is very hard to implement from scratch and you’ll have to write long lines of code in order to implement it but firebase makes it simple. In this article we will learn how to authenticate email and password using Firebase. We will start by setting up a project. After that, we will register a user and then we will log in with the same credentials to demonstrate the authentication.

Creating a login and registration page

Create ‘Login.js’ inside the ‘components’ folder and use the code below

import React, { useState } from 'react';
import { Form, Button, Container } from 'react-bootstrap';
import { useHistory } from 'react-router-dom';
import { auth } from '../firebase';

const Login = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const history = useHistory();

  const loginUser = (e) => {
    e.preventDefault();
    auth
      .signInWithEmailAndPassword(email, password)
      .then(() => {
        console.log('Logged in succesfully hurry...');
        history.push('/dashboard');
      })
      .catch((error) => alert(error.message));
  };

  return (
    <Container className='mt-5'>
      <h1 className='my-5 pt-5'>Login Page</h1>
      <Form>
        <Form.Group controlId='formBasicEmail'>
          <Form.Label>Email address</Form.Label>
          <Form.Control
            onChange={(e) => setEmail(e.target.value)}
            type='email'
		  value={email}
            placeholder='Enter email'
          />
        </Form.Group>

        <Form.Group controlId='formBasicPassword'>
          <Form.Label>Password</Form.Label>
          <Form.Control
            onChange={(e) => setPassword(e.target.value)}
		  value={password}
            type='password'
            placeholder='Password'
          />
        </Form.Group>
        <Form.Group controlId='formBasicCheckbox'>
          <Form.Check type='checkbox' label='Check me out' />
        </Form.Group>
        <Button variant='primary' type='submit' onClick={loginUser}>
          Submit
        </Button>
      </Form>
    </Container>
  );
};

export default Login;

Similarly create ‘Register.js’ inside ‘components’ folder and use the below code.

import React, { useState } from 'react';
import { Form, Button, Container } from 'react-bootstrap';
import { auth } from '../firebase';
import { useHistory } from 'react-router-dom';

const Register = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const history = useHistory();
  const registerUser = async (e) => {
    e.preventDefault();
    try {
      const user = await auth.createUserWithEmailAndPassword(email, password);
      if (user) {
        console.log('Congrats you just created a user');
        history.push('/dashboard');
      }
    } catch (err) {
      console.log('Error in signup process');
      console.log(err.message);
    }
  };
  return (
    <Container className='mt-5'>
      <h1 className='my-5 pt-5'>Register Page</h1>
      <Form>
        <Form.Group controlId='formBasicEmail'>
          <Form.Label>Email address</Form.Label>
          <Form.Control
            onChange={(e) => setEmail(e.target.value)}
            type='email'
		  value={email}
            placeholder='Enter email'
          />
        </Form.Group>

        <Form.Group controlId='formBasicPassword'>
          <Form.Label>Password</Form.Label>
          <Form.Control
            onChange={(e) => setPassword(e.target.value)}
            type='password'
		  value={password}
            placeholder='Password'
          />
        </Form.Group>
        <Form.Group controlId='formBasicCheckbox'>
          <Form.Check type='checkbox' label='Check me out' />
        </Form.Group>
        <Button onClick={registerUser} variant='primary' type='submit'>
          Submit
        </Button>
      </Form>
    </Container>
  );
};

export default Register;

 

Discussion