Share
Explore

REACT Lab with a Firebase Datastore

Find Working Code:

Documentation:
Adding Firebase to your App

Learning Outcomes:
Create a complete React application with Firebase support
Setting up of the environment
Creating the application
Integrating Firebase.
Running and testing the complete app, executing these instructions in your local development environment.

Step 1: Setting Up The Environment

You'll need Node.js and npm installed on your machine. You can download them from .

Step 2: Create a React App

Use create-react-app to bootstrap a new React project.
npx create-react-app my-firebase-app
cd my-firebase-app

Step 3: Install Firebase

Install Firebase via npm to make it available in your React app.
npm install firebase

Step 4: Create a Firebase Project

Go to the .
Click on "Add project" to create a new Firebase project.
Follow the instructions to set up the project.
Go to the Project settings to find your configuration text settings.

Step 5: Initialize Firebase in Your App

Create a file named firebase.js in your src folder to keep the Firebase configuration.
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';

const firebaseConfig = {
apiKey: "Your API Key",
authDomain: "Your Auth Domain",
projectId: "Your Project ID",
storageBucket: "Your Storage Bucket",
messagingSenderId: "Your Messaging Sender ID",
appId: "Your App ID"
};

firebase.initializeApp(firebaseConfig);

export default firebase;
Fill firebaseConfig with your project's configuration.

Step 6: Authentication

Let's add a simple email and password authentication.

src/AuthService.js

import firebase from './firebase';

export const signUp = (email, password) => {
return firebase.auth().createUserWithEmailAndPassword(email, password);
};

export const signIn = (email, password) => {
return firebase.auth().signInWithEmailAndPassword(email, password);
};

export const signOut = () => {
return firebase.auth().signOut();
};

Step 7: Create Components

Create some components for your app. For example, SignUp.js, SignIn.js, and Home.js.

src/SignUp.js

import React, { useState } from 'react';
import { signUp } from './AuthService';

function SignUp() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');

const handleSubmit = async (e) => {
e.preventDefault();
try {
await signUp(email, password);
alert('User created successfully!');
} catch (error) {
alert(error.message);
}
};

return (
<div>
<h1>Sign Up</h1>
<form onSubmit={handleSubmit}>
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" />
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Password" />
<button type="submit">Sign Up</button>
</form>
</div>
);
}

export default SignUp;
Repeat the similar process for SignIn.js and a homepage Home.js. The SignIn.js will be similar to SignUp.js, but for logging in existing users.
info

Below is an example of what the SignIn.js component could look like.

This component will handle user sign-in using their email and password.

import React, { useState } from 'react';
import { signIn } from './AuthService';
import { useHistory } from 'react-router-dom';

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

const handleSubmit = async (e) => {
e.preventDefault();
try {
await signIn(email, password);
// Redirect to the home page or dashboard after successful sign-in
history.push('/');
} catch (error) {
// Handle sign-in errors here, such as incorrect credentials
alert(error.message);
}
};

return (
<div>
<h1>Sign In</h1>
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Email"
required
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Password"
required
/>
<button type="submit">Sign In</button>
</form>
</div>
);
}

export default SignIn;
In this component:
We use the useState hook to manage the email and password state.
We use useHistory from react-router-dom to navigate to the home page upon successful sign-in.
The signIn function is imported from AuthService.js, which you would define to use Firebase's sign-in methods.
Upon form submission, the handleSubmit function attempts to sign in the user with the provided credentials. If successful, the user is redirected to the home page. If there is an error (e.g., incorrect credentials), it is displayed using an alert (consider using a more user-friendly error handling in a real application).
Please replace the placeholders in the AuthService.js with the Firebase authentication logic, and ensure your project is properly configured to redirect users after sign-in. Also, remember to handle state and error messages appropriately in a real-world application to improve user experience.

error

The Home.js component would typically be the main landing page after a user successfully logs in. For the purpose of simplicity, let's create a Home.js component that greets the user and provides a sign-out option.

Here is a basic example for Home.js:
import React, { useEffect, useState } from 'react';
import firebase from './firebase';
import { signOut } from './AuthService';
import { useHistory } from 'react-router-dom';

function Home() {
const [currentUser, setCurrentUser] = useState(null);
const history = useHistory();

useEffect(() => {
// Subscribe to auth state changes
const unsubscribe = firebase.auth().onAuthStateChanged(user => {
if (user) {
// User is signed in
setCurrentUser(user);
} else {
// No user is signed in, redirect to sign-in page
history.push('/signin');
}
});

// Cleanup subscription on unmount
return () => unsubscribe();
}, [history]);

const handleSignOut = async () => {
try {
await signOut();
history.push('/signin');
} catch (error) {
// Handle errors here - maybe show a notification or message
console.error('Sign out failed', error);
alert('Sign out failed: ' + error.message);
}
};

return (
<div>
<h1>Home</h1>
{currentUser && <p>Welcome, {currentUser.email}!</p>}
<button onClick={handleSignOut}>Sign Out</button>
</div>
);
}

export default Home;
In this Home.js component:
We use the useState and useEffect hooks to manage the current user's state and respond to changes in the authentication state.
We use the onAuthStateChanged method from Firebase to listen for changes in the user's authentication state.
If there is no authenticated user, we redirect to the sign-in page.
If the user is signed in, we display a greeting and a sign-out button.
The signOut function (not shown here) must be implemented in AuthService.js to handle the Firebase sign-out process.
Here's a simple implementation of the signOut function for AuthService.js:
import firebase from './firebase';

export const signOut = () => {
return firebase.auth().signOut();
};
Ensure that the ./firebase import points to the module where you have initialized your Firebase app and its auth module.

Step 8: Routing

Install React Router for navigation.
npm install react-router-dom
Configure your routes in App.js.

import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import SignUp from './SignUp';
import SignIn from './SignIn';
import Home from './Home';

function App() {
return (
<Router>
<Switch>
<Route path="/signup" component={SignUp} />
<Route path="/signin" component={SignIn} />
<Route path="/" component={Home} />
</Switch>
</Router>
);
}

export default App;
error

Here's what your App.js file might look like with routes set up for signing in, signing up, and the home page, including all the updates for handling the Firebase authentication state.

import React, { useEffect, useState } from 'react';
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';
import firebase from './firebase';
import SignUp from './SignUp'; // Import your SignUp component
import SignIn from './SignIn'; // Import your SignIn component
import Home from './Home'; // Import your Home component

function App() {
const [currentUser, setCurrentUser] = useState(null);
const [loading, setLoading] = useState(true);

useEffect(() => {
// Listen for auth state changes
const unsubscribe = firebase.auth().onAuthStateChanged(user => {
setCurrentUser(user);
setLoading(false);
});

// Clean up the listener on unmount
return unsubscribe;
}, []);

if (loading) {
// Possibly include some loading indicator while waiting for auth state
return <div>Loading...</div>;
}

return (
<Router>
<Switch>
<Route exact path="/" render={() => (
currentUser ? <Home /> : <Redirect to="/signin" />
)} />
<Route path="/signup" render={() => (
!currentUser ? <SignUp /> : <Redirect to="/" />
)} />
<Route path="/signin" render={() => (
!currentUser ? <SignIn /> : <Redirect to="/" />
)} />
{/* Redirect all other paths to the home page, update as needed */}
<Route render={() => <Redirect to="/" />} />
</Switch>
</Router>
);
}

export default App;
Explanation of code:
We use useState to keep track of the currentUser and a loading state to handle the asynchronous nature of Firebase authentication status checking.
The useEffect hook sets up a listener for Firebase auth state changes. If the user is logged in, the currentUser state is updated, and when the user logs out, it's set to null.
The loading state is used to display a loading indicator until the Firebase auth state is confirmed.
We use BrowserRouter (Router) and Switch from react-router-dom to define our routing.
The Route components determine which page to display based on the URL path.
We use render props to conditionally render Redirect components depending on whether the user is authenticated, ensuring users can only access certain pages if they are signed in or not.
This setup uses conditional rendering within Route's render prop to redirect users based on authentication state.
The loading state allows you to put a loading screen or spinner until the authentication state is known, avoiding flickering of components which require user to be authenticated.
Remember to replace './firebase' with the path to your Firebase configuration file where Firebase is initialized, and ensure that the SignUp, SignIn, and Home components are correctly implemented as per the instructions I have previously outlined.

Step 9: Running the App

To run the app, use this command:
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.