Open In App

How to implement Email Registration and Login using Firebase in React?

Improve
Improve
Like Article
Like
Save
Share
Report

When building a full-stack application we sometimes want to do build the authentication part quickly without writing much code, then there comes Firebase to our rescue which offers multiple authentication methods like Email-Password, Google, Facebook, etc.

Following are the steps which cover how to authenticate users through email id and password in React.js.

Getting Started: 

Step 1: Go to the firebase official site and set up the Firebase project as shown below.

Setting Up Firebase Project

Step 2: Now enable Email-Password Login in the authentication section.

Enable email/password authentication 

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app firebase_login

Step 2: Install all the necessary packages by running the following command:

npm i react-router-dom firebase

Project Structure:

Firebase Code:

Filename: firebase.js

Create a firebase.js file where we will initialize our firebase app and paste our firebase config credentials in firebaseConfig.

Javascript




import firebaseConfig from '../config';
import firebase from 'firebase/app';
  
const firebaseConfig = { 
    apiKey: "*******"
    authDomain: "*******",  
    projectId: "*******"
    storageBucket: "*******"
    messagingSenderId: "*******",  
    appId: "*******",
    measurementId: "*******" 
};
  
firebase.initializeApp(firebaseConfig); 
export const auth = firebase.auth();


Filename: Auth.js

Create a auth.js file where we will create our register and login methods for firebase.

Javascript




import firebase from 'firebase/app';
import "firebase/auth"
import {auth} from './firebase'
  
export const register = async({email, password})=>{
    const resp = await firebase.auth()
      .createUserWithEmailAndPassword(email, password);
    return resp.user;
}
  
export const login = async({email, password})=>{
    const res = await firebase.auth()
      .signInWithEmailAndPassword(email, password);
    return res.user;
}


Login/Registration Components:

Filename:Register.js

Create a Register.js file for the registration component where we will handle the registration.

Javascript




import React, {useState} from 'react'
import {register} from './auth'
  
const Register = () => {
    const [form,setForm] = useState({
        email:'',
        password:''
    })
    const handleSubmit = async(e)=>{
        e.preventDefault();
        await register(form);
  
    }
    const InputFields = {
        padding:'0.5rem',
        margin:'0.8rem',
        borderRadius: '4px'
    }
    const ButtonStyle = {
        borderRadius: '4px',
        padding:'0.7rem',
        margin:'0.5rem'
    }
    return (
        <div>
            <h1>Register</h1>
            <form onSubmit={handleSubmit} >
            <label for="email">Email</label>
            <input type="text" style={InputFields}
                   placeholder="email" id="mail" 
            onChange={(e) => 
            setForm({...form, email: e.target.value})} />
            <br/>
            <label for="password">Password</label>
            <input type="password"  placeholder="Password" 
                   style={InputFields} 
            onChange={(e) => 
            setForm({...form, password: e.target.value})}/>
            <br/>
            <button type="submit" style={ButtonStyle}>
                Submit
            </button>
            </form>
        </div>
  
    )
}
  
export default Register


Filename: Login.js

Create a Login.js file for the login component where we will handle the login.

Javascript




import React, {useState} from 'react'
import {login} from './auth'
  
const Login = () => {
    const [form,setForm] = useState({
        email:'',
        password:''
    })
    const handleSubmit = async(e)=>{
        e.preventDefault();
        await login(form);
  
    }
    const InputFields = {
        padding:'0.5rem',
        margin:'0.8rem',
        borderRadius: '4px'
    }
    const ButtonStyle = {
        borderRadius: '4px',
        padding:'0.7rem',
        margin:'0.5rem'
    }
    return (
        <div>
            <h1>Login</h1>
            <form onSubmit={handleSubmit} >
            <label for="email">Email</label>
            <input type="text" style={InputFields}
                   placeholder="email" id="mail" 
            onChange={(e) => 
            setForm({...form, email: e.target.value})} />
            <br/>
            <label for="password">Password</label>
            <input type="password"  placeholder="Password" 
                   style={InputFields} 
            onChange={(e) => 
            setForm({...form, password: e.target.value})}/>
            <br/>
            <button type="submit" style={ButtonStyle}>
                   Submit
            </button>
            </form>
        </div>
  
    )
}
  
export default Login


Handling Routes in App.js:-

Filename: App.js

Javascript




import {useState} from 'react';
import './App.css';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import Login from './login';
import Register from './register';
  
function App() {
  
  return (
    <Router>
    <div className="App">
      <Route exact path='/register' component={Register} />
      <Route exact path='/login' component={Login} />
     </div>
     </Router>
  );
}
  
export default App;


Steps to Run Application:

 Run the application using the following command from the root directory of the project.

npm start

Output:

  • We can now register users through the registration form by going to the http://localhost:3000/register route in the browser.

  • We can verify that the user was registered successfully by checking the authentication section of the firebase.

  • Users can also login  by going to http://localhost:3000/login route in the browser.

Now our Login and Registration components are done which will easily handle authentication using firebase.



Last Updated : 28 Dec, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads