0
0
React Nativemobile~20 mins

Realtime Database in React Native - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Realtime Chat
A simple chat screen that shows messages from a realtime database and allows sending new messages.
Target UI
-------------------------
| Realtime Chat         |
-------------------------
| [Message list here]   |
|                       |
| --------------------- |
| | Type message...   | |
| | [Send Button]     | |
-------------------------
Display a list of chat messages from a realtime database.
Listen for new messages and update the list in real time.
Provide a text input to type a new message.
Send button adds the message to the database and clears input.
Use Firebase Realtime Database for data storage.
Starter Code
React Native
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Button, FlatList, StyleSheet } from 'react-native';
import database from '@react-native-firebase/database';

export default function RealtimeChat() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');

  useEffect(() => {
    // TODO: Add listener to fetch messages from realtime database
  }, []);

  const sendMessage = () => {
    // TODO: Add code to send message to realtime database
  };

  return (
    <View style={styles.container}>
      <FlatList
        data={messages}
        keyExtractor={item => item.id}
        renderItem={({ item }) => <Text style={styles.message}>{item.text}</Text>}
      />
      <View style={styles.inputContainer}>
        <TextInput
          style={styles.input}
          placeholder="Type message..."
          value={input}
          onChangeText={setInput}
        />
        <Button title="Send" onPress={sendMessage} />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 16 },
  message: { padding: 8, fontSize: 16 },
  inputContainer: { flexDirection: 'row', alignItems: 'center' },
  input: { flex: 1, borderColor: '#ccc', borderWidth: 1, padding: 8, marginRight: 8, borderRadius: 4 }
});
Task 1
Task 2
Solution
React Native
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Button, FlatList, StyleSheet } from 'react-native';
import database from '@react-native-firebase/database';

export default function RealtimeChat() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');

  useEffect(() => {
    const messagesRef = database().ref('/messages');
    const onValueChange = messagesRef.on('value', snapshot => {
      const data = snapshot.val() || {};
      const parsedMessages = Object.entries(data).map(([id, value]) => ({ id, text: value.text }));
      setMessages(parsedMessages);
    });
    return () => messagesRef.off('value', onValueChange);
  }, []);

  const sendMessage = () => {
    if (input.trim().length === 0) return;
    const messagesRef = database().ref('/messages');
    messagesRef.push({ text: input.trim() });
    setInput('');
  };

  return (
    <View style={styles.container}>
      <FlatList
        data={messages}
        keyExtractor={item => item.id}
        renderItem={({ item }) => <Text style={styles.message}>{item.text}</Text>}
      />
      <View style={styles.inputContainer}>
        <TextInput
          style={styles.input}
          placeholder="Type message..."
          value={input}
          onChangeText={setInput}
          accessibilityLabel="Message input"
          accessible={true}
        />
        <Button title="Send" onPress={sendMessage} accessibilityLabel="Send message button" />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 16, backgroundColor: '#fff' },
  message: { padding: 8, fontSize: 16, borderBottomColor: '#eee', borderBottomWidth: 1 },
  inputContainer: { flexDirection: 'row', alignItems: 'center', marginTop: 8 },
  input: { flex: 1, borderColor: '#ccc', borderWidth: 1, padding: 8, marginRight: 8, borderRadius: 4 }
});

This React Native component connects to Firebase Realtime Database to show a live chat.

Inside useEffect, it sets a listener on the /messages path. When data changes, it updates the messages state with the latest messages.

The sendMessage function pushes a new message to the database and clears the input field.

Accessibility labels are added for screen readers. The UI uses a FlatList to efficiently render messages and a text input with a send button below.

Final Result
Completed Screen
-------------------------
| Realtime Chat         |
-------------------------
| Hello!                |
| How are you?          |
| I'm fine, thanks!     |
|                       |
| --------------------- |
| | Type message...   | |
| | [Send Button]     | |
-------------------------
When the app loads, it shows all messages from the database.
If a new message is added by anyone, the list updates immediately.
Typing in the input and pressing Send adds the message to the chat and clears the input.
Stretch Goal
Add a loading indicator while messages are loading from the database.
💡 Hint
Use a state variable to track loading and show an ActivityIndicator component until messages load.