Firebase is a powerful platform that provides backend services such as real-time databases, authentication, and hosting. In this article, we'll walk you through integrating Firebase Authentication and Firebase Firestore (a real-time NoSQL database) into a React app. This integration will allow you to handle user authentication and store/retrieve data with ease.
Prerequisites
Before we start, ensure that you have:
- A Firebase account and project set up in the Firebase console.
- Node.js and npm installed on your system.
- A basic understanding of React.
Step 1: Set Up Firebase Project
1. Go to the Firebase Console: Firebase Console.
2. Create a New Project: Click on "Add Project" and follow the instructions.
3. Enable Firebase Authentication:
- In the Firebase console, select your project.
- Navigate to "Authentication" in the left sidebar and click "Get Started."
- Enable the sign-in methods you need (e.g., Email/Password, Google, Facebook).
4. Set Up Firestore:
- In the Firebase console, go to "Firestore Database" in the left sidebar.
- Click "Create Database" and follow the instructions to set up Firestore in test mode or production mode.
5. Get Firebase Config:
- From the Firebase console, go to Project Settings (click the gear icon).
- Under "Your apps," select "Web" and copy the Firebase config object that includes
apiKey
,authDomain
,projectId
, etc.
Step 2: Install Firebase SDK in Your React App
In your React project, you'll need to install Firebase using npm:
npm install firebase
Step 3: Set Up Firebase in Your React Project
Create a firebase.js file to configure Firebase services (authentication and Firestore):
// src/firebase.js
import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";
// Add your Firebase config here
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",
measurementId: "YOUR_MEASUREMENT_ID"
};
// Initialize Firebase
const firebaseApp = firebase.initializeApp(firebaseConfig);
// Get Firestore database and Authentication instances
const db = firebaseApp.firestore();
const auth = firebaseApp.auth();
export { db, auth };
This configuration allows you to access Firebase's Firestore database and Authentication services.
Step 4: Setting Up Authentication in React
We'll now set up a simple sign-up and login form using Firebase Authentication.
1. Creating a Sign-Up Component
// src/components/SignUp.js
import React, { useState } from 'react';
import { auth } from '../firebase';
const SignUp = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const handleSignUp = async (e) => {
e.preventDefault();
try {
await auth.createUserWithEmailAndPassword(email, password);
setEmail('');
setPassword('');
} catch (error) {
setError(error.message);
}
};
return (
<div>
<h2>Sign Up</h2>
<form onSubmit={handleSignUp}>
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
<button type="submit">Sign Up</button>
</form>
{error && <p>{error}</p>}
</div>
);
};
export default SignUp;
2. Creating a Login Component
// src/components/Login.js
import React, { useState } from 'react';
import { auth } from '../firebase';
const Login = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const handleLogin = async (e) => {
e.preventDefault();
try {
await auth.signInWithEmailAndPassword(email, password);
setEmail('');
setPassword('');
} catch (error) {
setError(error.message);
}
};
return (
<div>
<h2>Login</h2>
<form onSubmit={handleLogin}>
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
<button type="submit">Log In</button>
</form>
{error && <p>{error}</p>}
</div>
);
};
export default Login;
Step 5: Setting Up Firestore Database in React
Now that the authentication is working, let’s focus on how to use Firestore for storing and retrieving data.
1. Adding Data to Firestore
Create a component to add data to the Firestore database.
// src/components/AddData.js
import React, { useState } from 'react';
import { db } from '../firebase';
const AddData = () => {
const [data, setData] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
await db.collection('data').add({
content: data,
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
});
setData('');
} catch (error) {
console.error("Error adding document: ", error);
}
};
return (
<div>
<h2>Add Data</h2>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Enter data"
value={data}
onChange={(e) => setData(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
</div>
);
};
export default AddData;
2. Retrieving Data from Firestore
To display the data stored in Firestore:
// src/components/DisplayData.js
import React, { useEffect, useState } from 'react';
import { db } from '../firebase';
const DisplayData = () => {
const [data, setData] = useState([]);
useEffect(() => {
const unsubscribe = db.collection('data')
.orderBy('timestamp', 'desc')
.onSnapshot(snapshot => {
setData(snapshot.docs.map(doc => doc.data()));
});
return unsubscribe;
}, []);
return (
<div>
<h2>Data</h2>
{data.map((item, index) => (
<p key={index}>{item.content}</p>
))}
</div>
);
};
export default DisplayData;
Step 6: Putting It All Together
Now, you can combine these components in your App.js to create a simple React app that handles both authentication and stores/retrieves data:
// src/App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import SignUp from './components/SignUp';
import Login from './components/Login';
import AddData from './components/AddData';
import DisplayData from './components/DisplayData';
function App() {
return (
<Router>
<Switch>
<Route path="/signup" component={SignUp} />
<Route path="/login" component={Login} />
<Route path="/add" component={AddData} />
<Route path="/data" component={DisplayData} />
</Switch>
</Router>
);
}
export default App;
Conclusion
Firebase makes it incredibly easy to integrate authentication and databases into your React applications. By using Firebase Authentication, you can handle user registration, login, and session management with minimal setup. Firebase Firestore allows you to store and sync data in real-time without the need for a backend server.
Now that you have a foundational setup for Firebase in React, you can continue to explore advanced Firebase features such as cloud functions, file storage, and more to enhance your applications.
Top comments (0)