Step1 : Install Firebase SDK
npm install firebase
Step 2: Initialize Firebase
// src/firebase.js
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getDatabase } from "firebase/database";
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",
databaseURL: "YOUR_DATABASE_URL"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getDatabase(app);
export { auth, db };
Step 3 : create chat component
// src/components/Chat.js
import React, { useEffect, useState } from 'react';
import { db } from '../firebase';
import { ref, push, onValue } from 'firebase/database';
const Chat = () => {
const [messages, setMessages] = useState([]);
const [newMessage, setNewMessage] = useState('');
useEffect(() => {
const messagesRef = ref(db, 'messages');
onValue(messagesRef, (snapshot) => {
const data = snapshot.val();
const messagesList = [];
for (let id in data) {
messagesList.push({ id, ...data[id] });
}
setMessages(messagesList);
});
}, []);
const handleSendMessage = async (e) => {
e.preventDefault();
if (newMessage.trim()) {
const messagesRef = ref(db, 'messages');
await push(messagesRef, {
text: newMessage,
timestamp: new Date().toISOString(),
});
setNewMessage('');
}
};
return (
<div>
<div>
{messages.map((message) => (
<p key={message.id}>{message.text}</p>
))}
</div>
<form onSubmit={handleSendMessage}>
<input
type="text"
value={newMessage}
onChange={(e) => setNewMessage(e.target.value)}
placeholder="Type a message"
/>
<button type="submit">Send</button>
</form>
</div>
);
};
export default Chat;
Step 4 : Auth component
// src/components/SignIn.js
import React, { useState } from 'react';
import { auth } from '../firebase';
import { signInWithEmailAndPassword } from 'firebase/auth';
const SignIn = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
await signInWithEmailAndPassword(auth, email, password);
} catch (error) {
console.error("Error signing in", error);
}
};
return (
<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 In</button>
</form>
);
};
export default SignIn;
Step 5 : App modification
// src/App.js
import React, { useEffect, useState } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import SignIn from './components/SignIn';
import Chat from './components/Chat';
import { auth } from './firebase';
import { onAuthStateChanged } from 'firebase/auth';
const App = () => {
const [user, setUser] = useState(null);
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
if (user) {
setUser(user);
} else {
setUser(null);
}
});
return () => unsubscribe();
}, []);
return (
<Router>
<Switch>
<Route path="/chat">
{user ? <Chat /> : <SignIn />}
</Route>
<Route path="/">
<SignIn />
</Route>
</Switch>
</Router>
);
};
export default App;