import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, TouchableOpacity, FlatList, StyleSheet, Image, StatusBar } from 'react-native';
import auth from '@react-native-firebase/auth';
import firestore from '@react-native-firebase/firestore';
const WhatsAppClone = () => {
const [message, setMessage] = useState('');
const [messages, setMessages] = useState([]);
const [user, setUser] = useState(null);
// Sign in anonymously
useEffect(() => {
const unsubscribeAuth = auth().onAuthStateChanged(user => {
if (user) {
setUser(user);
} else {
auth().signInAnonymously();
}
});
return unsubscribeAuth;
}, []);
// Load messages
useEffect(() => {
if (!user) return;
const unsubscribeMessages = firestore()
.collection('messages')
.orderBy('createdAt', 'desc')
.limit(50)
.onSnapshot(querySnapshot => {
const loadedMessages = [];
querySnapshot.forEach(doc => {
loadedMessages.push({
id: doc.id,
...doc.data(),
});
});
setMessages(loadedMessages.reverse());
});
return unsubscribeMessages;
}, [user]);
const sendMessage = async () => {
if (!message.trim() || !user) return;
await firestore().collection('messages').add({
text: message,
createdAt: firestore.FieldValue.serverTimestamp(),
userId: user.uid,
});
setMessage('');
};
const renderMessage = ({ item }) => {
const isCurrentUser = item.userId === user?.uid;
return (
{item.text}
{item.createdAt?.toDate()?.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
);
};
return (
WhatsApp Clone
item.id}
contentContainerStyle={styles.messagesList}
inverted
/>
Send
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#ECE5DD',
},
header: {
backgroundColor: '#075E54',
padding: 15,
paddingTop: 40,
flexDirection: 'row',
alignItems: 'center',
},
headerTitle: {
color: 'white',
fontSize: 20,
fontWeight: 'bold',
},
messagesList: {
padding: 10,
},
messageContainer: {
maxWidth: '80%',
padding: 10,
borderRadius: 8,
marginBottom: 10,
},
currentUserMessage: {
alignSelf: 'flex-end',
backgroundColor: '#DCF8C6',
borderTopRightRadius: 0,
},
otherUserMessage: {
alignSelf: 'flex-start',
backgroundColor: 'white',
borderTopLeftRadius: 0,
},
messageText: {
fontSize: 16,
},
timeText: {
fontSize: 12,
color: '#666',
alignSelf: 'flex-end',
marginTop: 5,
},
inputContainer: {
flexDirection: 'row',
padding: 10,
backgroundColor: 'white',
alignItems: 'center',
},
input: {
flex: 1,
borderWidth: 1,
borderColor: '#ddd',
borderRadius: 20,
paddingHorizontal: 15,
paddingVertical: 10,
marginRight: 10,
backgroundColor: 'white',
},
sendButton: {
backgroundColor: '#075E54',
borderRadius: 20,
paddingVertical: 10,
paddingHorizontal: 20,
},
sendButtonText: {
color: 'white',
fontWeight: 'bold',
},
});
export default WhatsAppClone;