Authentication using firebase in React js
By: Aniket Shelar
Tags: Authentication, Bootstrap, React, Firebase

In this blog, we are going to learn how to create Login and User Registration functionalities using Firebase Authentication services in React js.

We will start by setting up a new react app from scratch, create a new Firebase project, implement Firebase in a react app.

We will also create login and registration form for submit user credentials in firebase. Next, we will access the Firebase authentication APIs from react js components to login and register users.

You should have Node & NPM set up on our device.

Install React js Project

Write this command in your command prompt. Before writing this command you can select directory (Folder) where you want to install your React project.

npx create-react-app login-using-firebase

cd login-using-firebase

Add React Bootstrap in Project

React Bootstrap is use for designing the web pages.

npm install react-bootstrap bootstrap

Firebase Account Setup

Visit firebase console to create a Firebase project.

Create Firebase account from Firebase dashboard. Click on “Create a project” button and create a new Firebase authentication project.

Enter project name and click on the “Continue” button.

Write App nickname and click on “Next” button.

Click on “Continue to console” button to come in console page.

Now, Enable email/password in firebase for that

goto Authentication

Click on Sign-in method and enable Email/Password.

Add Navigation in React App

We need to add navigation to navigate between pages by click.

Add react-router-dom package in your project.

npm install react-router-dom

Create a folder “Component” in src folder and create “Navigation.js” file in services folder

And add the following code in Navigation.js file

Navigation.js

import React from 'react' import { Route, Switch } from 'react-router-dom' import Login from './login' import Register from './register' export default function Navigation() { return ( <Switch> <Route path="/" exact component={Login} /> <Route path="/register" component={Register} /> </Switch> ) }

Add “history” package in your project.

npm install history

Create a folder “Services” in src folder and create “history.js” file in services folder.

history.js

import { createBrowserHistory } from 'history'; const history = createBrowserHistory(); export default history;

Add following code in App.js file

import React from 'react'; import 'bootstrap/dist/css/bootstrap.min.css'; import Navigation from './component/Navigation'; import { Router } from 'react-router-dom'; import history from './Services/history'; function App() { return ( <Router history={history}> <Navigation /> </Router> ); } export default App;

Set up Firebase in React App

We need to set up and configure Firebase in our react application using a third party Firebase package.

Run the following command to install the Firebase package in your project.

npm install firebase

Now you run your project on browser. For that you run following command

npm start

Create “firebase.js” file in “Services” folder. And add the following code.

import firebase from 'firebase'; const firebaseConfig = { apiKey: "<apiKey>", authDomain: "<authDomain>", projectId: "<projectId>", storageBucket: "<storageBucket>", messagingSenderId: "<messagingSenderId>", appId: "<appId>" }; firebase.initializeApp(firebaseConfig); export default firebase;

Now, we have successfully configured Firebase in react app. We are now able to access the Firebase authentication services via its APIs.

Add CSS for web design

Add CSS for form design we are also using bootstrap for design.

Add the following code in App.css file

App.css

.text-centre { text-align: center; } .text-right { text-align: right; } .small-text { font-size: 15px; } .black-text { color: #000; } .response-text { color: green; } .padding-20 { padding: 20px; } .align-login-item-centre { padding-top: 10%; } .align-register-item-centre { padding-top: 9%; } .box { background-color: white; border: 1px solid; border-radius: 25px; padding: 15px; box-shadow: 5px 10px #888888; }

Register with Email and Password

In this step, we will learn how to implement Firebase User Authentication in React js application. We will create a basic form in our react js app, and It will have a name, username and password values.

Create a “register.js” file in “Component” folder.

Add the following code in register.js file

register.js

import React, { useState } from 'react' import '../App.css'; import { Container, Row, Col, Button } from 'react-bootstrap'; import firebase from '../Services/firebase'; function Register() { const [registerForm, setRegisterForm] = useState({ name: '', username: '', password: '' }) const [response, setResponse] = useState(); const onChangeName = (value) => { registerForm.name = value; } const onChangeUserName = (value) => { registerForm.username = value; } const onChangePassword = (value) => { registerForm.password = value; } const onRegister = () => { firebase .auth() .createUserWithEmailAndPassword(registerForm.username, registerForm.password) .then((res) => { setResponse('User registered successfully!') }) .catch((res) => { setResponse('User registration failed!') }) } return ( <div> <div class="align-register-item-centre"> <Container> <Row> <Col md = {4}></Col> <Col md = {4}> <div class="box"> <h1 class="text-centre black-text">Register</h1> {(response)?<h6 class="error-text text-centre">{response}</h6>:<div></div>} <br /> <label class="black-text small-text">Name:</label> <input type="text" class="form-control" onChange={(e) => onChangeName(e.target.value)}/> <label class="black-text small-text">Username:</label> <input type="text" class="form-control" onChange={(e) => onChangeUserName(e.target.value)}/> <label class="black-text small-text">Password:</label> <input type="password" class="form-control" onChange={(e) => onChangePassword(e.target.value)}/> <br /> <Button variant="primary" block onClick={() => onRegister()}>Register</Button> <p class="text-centre black-text small-text"><a href="/">You have account ?</a></p> </div> </Col> <Col md = {4}></Col> </Row> </Container> </div> </div> ) }

export default Register;

fill the form and click on Register button, data will be added on firebase Authentication in user section.

Login User with email and password

In this step, we will learn how login in react application using username and password.

Create a “login.js” file in “Component” folder.

Add the following code in login.js file

login.js

import React, { useState } from 'react' import '../App.css'; import { Container, Row, Col, Button } from 'react-bootstrap'; import firebase from '../Services/firebase'; function Login() { const [loginForm, setLoginForm] = useState({ username: '', password: '' }) const [response, setResponse] = useState()

const onChangeUserName = (value) => { loginForm.username = value; } const onChangePassword = (value) => { loginForm.password = value; } const onLogin = () => { firebase .auth() .signInWithEmailAndPassword(loginForm.username, loginForm.password) .then((res) => { setResponse('User logged-in successfully!'); }) .catch((res) => { setResponse('User logged-in failed!') }) } return ( <div> <div class="align-login-item-centre"> <Container> <Row> <Col md = {4}></Col> <Col md = {4}> <div class="box"> <h1 class="text-centre black-text">Login Page</h1> {(response)?<h6 class="response-text text-centre">{response}</h6>:<div></div>} <br /> <label class="black-text small-text">username:</label> <input type="text" class="form-control" onChange={(e) => onChangeUserName(e.target.value)}/> <label class="black-text small-text">password:</label> <input type="password" class="form-control" onChange={(e) => onChangePassword(e.target.value)}/> <br /> <Button variant="primary" block onClick={() => onLogin()}>Login</Button> <p class="text-centre black-text small-text"> <a href="register">Don't have acount? click here to register</a></p> </div> </Col> <Col md = {4}></Col> </Row> </Container> </div> </div> ) } export default Login;

Fill the username and password then detail will checked in firebase Authentication users section and gives the response.