Day 2: Building the User Interface for a Chat App


Today, you’ll design the user interface for the chat application. This includes creating the chat screen layout and setting up a list to display messages dynamically.

What You Will Do Today:

  1. Install and configure React Native components for the UI.
  2. Create the chat screen layout with message input and a message list.
  3. Design reusable components for messages.

Step 1: Install Required Libraries

  1. Install React Native Gesture Handler and Keyboard Avoidance:
   npm install react-native-gesture-handler react-native-keyboard-aware-scroll-view
  1. Link the libraries for iOS (optional if using React Native 0.60+ with auto-linking):
   cd ios
   pod install
   cd ..

Step 2: Set Up the Chat Screen

  1. Create a ChatScreen.js file in the screens folder.
   // screens/ChatScreen.js
   import React, { useState } from 'react';
   import { View, TextInput, Button, FlatList, Text, StyleSheet } from 'react-native';
   import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';

   function ChatScreen() {
     const [messages, setMessages] = useState([]);
     const [text, setText] = useState('');

     const sendMessage = () => {
       if (text.trim()) {
         const newMessage = {
           id: Date.now().toString(),
           text,
           createdAt: new Date(),
           user: { id: '1', name: 'User' },
         };
         setMessages((prevMessages) => [newMessage, ...prevMessages]);
         setText('');
       }
     };

     const renderMessage = ({ item }) => (
       <View style={styles.messageContainer}>
         <Text style={styles.messageText}>{item.text}</Text>
         <Text style={styles.messageTimestamp}>
           {item.createdAt.toLocaleTimeString()}
         </Text>
       </View>
     );

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

   const styles = StyleSheet.create({
     container: {
       flex: 1,
       backgroundColor: '#f5f5f5',
     },
     messageList: {
       flex: 1,
       paddingHorizontal: 10,
     },
     messageContainer: {
       marginVertical: 8,
       padding: 10,
       backgroundColor: '#e1ffc7',
       borderRadius: 8,
       alignSelf: 'flex-start',
     },
     messageText: {
       fontSize: 16,
     },
     messageTimestamp: {
       fontSize: 12,
       color: '#888',
       marginTop: 4,
       alignSelf: 'flex-end',
     },
     inputContainer: {
       flexDirection: 'row',
       padding: 10,
       borderTopWidth: 1,
       borderTopColor: '#ddd',
       backgroundColor: '#fff',
     },
     input: {
       flex: 1,
       borderWidth: 1,
       borderColor: '#ddd',
       borderRadius: 8,
       paddingHorizontal: 10,
       marginRight: 10,
     },
   });

   export default ChatScreen;

Step 3: Update Navigation to Include Chat Screen

  1. In App.js, add ChatScreen to the navigation stack:
   import React from 'react';
   import { NavigationContainer } from '@react-navigation/native';
   import { createStackNavigator } from '@react-navigation/stack';
   import ChatScreen from './screens/ChatScreen';

   const Stack = createStackNavigator();

   export default function App() {
     return (
       <NavigationContainer>
         <Stack.Navigator>
           <Stack.Screen name="Chat" component={ChatScreen} options={{ title: 'Chat' }} />
         </Stack.Navigator>
       </NavigationContainer>
     );
   }

Step 4: Run and Test the Chat UI

  1. Start the app:
  • For Android: npx react-native run-android
  • For iOS: npx react-native run-ios
  1. Test the Chat Screen:
  • Type a message in the input box and press Send.
  • The message should appear in the chat bubble above the input.
  • Test the keyboard behavior to ensure it adjusts appropriately.
See also  Day 6: Sending Notifications When a New Message Is Received

Step 5: Customizing Message Bubbles (Optional)

  1. Create a reusable MessageBubble component:
   // components/MessageBubble.js
   import React from 'react';
   import { View, Text, StyleSheet } from 'react-native';

   function MessageBubble({ message }) {
     return (
       <View style={styles.container}>
         <Text style={styles.text}>{message.text}</Text>
         <Text style={styles.timestamp}>
           {message.createdAt.toLocaleTimeString()}
         </Text>
       </View>
     );
   }

   const styles = StyleSheet.create({
     container: {
       padding: 10,
       backgroundColor: '#e1ffc7',
       borderRadius: 8,
       marginVertical: 8,
       alignSelf: 'flex-start',
     },
     text: {
       fontSize: 16,
     },
     timestamp: {
       fontSize: 12,
       color: '#888',
       marginTop: 4,
       alignSelf: 'flex-end',
     },
   });

   export default MessageBubble;
  1. Update ChatScreen.js to use MessageBubble:
   import MessageBubble from '../components/MessageBubble';

   const renderMessage = ({ item }) => <MessageBubble message={item} />;

Summary

Today, you built the user interface for the chat application, including a message list, input box, and send button. You also created a reusable message bubble component to style messages consistently.

Tomorrow, you’ll implement real-time messaging with Firebase Firestore.


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.