React and Firebase make a powerful combination for building modern web applications. Firebase provides robust backend services like authentication, database, and hosting, while React enables creating dynamic and responsive user interfaces. In this tutorial, we’ll build a React application with Firebase Authentication and implement CRUD (Create, Read, Update, Delete) operations using Firestore.
Prerequisites
Before starting, ensure you have the following:
- Node.js installed on your system.
- Firebase account and access to the Firebase Console.
- Basic understanding of JavaScript, React, and Firebase.
- A text editor like Visual Studio Code.
Step 1: Setting Up the Firebase Project
1.1 Create a Firebase Project
Go to the Firebase Console.
Click on Add Project and follow the setup wizard.
Enable Firestore Database in the Build section.
Enable Authentication and configure an email/password provider in the Sign-in method tab.
1.2 Add a Web App
In the Firebase Console, select your project.
Click on Add App and select Web App.
Register the app and copy the Firebase configuration details.
Step 2: Setting Up the React Project
2.1 Initialize React App
Open your terminal and create a new React app:
npx create-react-app react-firebase-crud
cd react-firebase-crud
Install Firebase SDK:
npm install firebase
2.2 Configure Firebase
Create a firebase.js file in the src folder:
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import { getFirestore } from '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',
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
export { auth, db };
Step 3: Authentication System
3.1 Create Authentication Pages
Create a components folder inside src and add two files: Login.js and Register.js.
Register.js
import React, { useState } from 'react';
import { createUserWithEmailAndPassword } from 'firebase/auth';
import { auth } from '../firebase';
const Register = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleRegister = async (e) => {
e.preventDefault();
try {
await createUserWithEmailAndPassword(auth, email, password);
alert('User registered successfully!');
} catch (error) {
console.error(error.message);
}
};
return (
<form onSubmit={handleRegister}>
<input type="email" placeholder="Email" onChange={(e) => setEmail(e.target.value)} />
<input type="password" placeholder="Password" onChange={(e) => setPassword(e.target.value)} />
<button type="submit">Register</button>
</form>
);
};
export default Register;
Login.js
import React, { useState } from 'react';
import { signInWithEmailAndPassword } from 'firebase/auth';
import { auth } from '../firebase';
const Login = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleLogin = async (e) => {
e.preventDefault();
try {
await signInWithEmailAndPassword(auth, email, password);
alert('Logged in successfully!');
} catch (error) {
console.error(error.message);
}
};
return (
<form onSubmit={handleLogin}>
<input type="email" placeholder="Email" onChange={(e) => setEmail(e.target.value)} />
<input type="password" placeholder="Password" onChange={(e) => setPassword(e.target.value)} />
<button type="submit">Login</button>
</form>
);
};
export default Login;
Step 4: CRUD Operations
4.1 Create a Firestore Collection
In the Firebase Console, go to Firestore Database, create a collection named tasks, and add sample documents.
4.2 Add CRUD Functions
Create a TaskManager.js component:
import React, { useState, useEffect } from 'react';
import { collection, addDoc, getDocs, updateDoc, deleteDoc, doc } from 'firebase/firestore';
import { db } from '../firebase';
const TaskManager = () => {
const [tasks, setTasks] = useState([]);
const [newTask, setNewTask] = useState('');
const fetchTasks = async () => {
const querySnapshot = await getDocs(collection(db, 'tasks'));
const tasksArray = querySnapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() }));
setTasks(tasksArray);
};
useEffect(() => {
fetchTasks();
}, []);
const handleAddTask = async () => {
if (newTask) {
await addDoc(collection(db, 'tasks'), { name: newTask });
fetchTasks();
setNewTask('');
}
};
const handleUpdateTask = async (id) => {
const taskDoc = doc(db, 'tasks', id);
await updateDoc(taskDoc, { name: newTask });
fetchTasks();
};
const handleDeleteTask = async (id) => {
const taskDoc = doc(db, 'tasks', id);
await deleteDoc(taskDoc);
fetchTasks();
};
return (
<div>
<input value={newTask} onChange={(e) => setNewTask(e.target.value)} placeholder="New Task" />
<button onClick={handleAddTask}>Add Task</button>
<ul>
{tasks.map((task) => (
<li key={task.id}>
{task.name}
<button onClick={() => handleUpdateTask(task.id)}>Update</button>
<button onClick={() => handleDeleteTask(task.id)}>Delete</button>
</li>
))}
</ul>
</div>
);
};
export default TaskManager;
Step 5: Routing
Install React Router:
npm install react-router-dom
Add routing in App.js:
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Login from './components/Login';
import Register from './components/Register';
import TaskManager from './components/TaskManager';
function App() {
return (
<Router>
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
<Route path="/tasks" element={<TaskManager />} />
</Routes>
</Router>
);
}
export default App;
Step 6: Run the Application
Start the development server:
npm start
Open the application in your browser and test the authentication and CRUD functionalities. Hope this is helpful, and I apologize if there are any inaccuracies in the information provided.
Post a Comment for "Building a React and Firebase Authentication System with CRUD Operations"