Building a chat application can be a complex task, but with the power of React, it becomes a lot easier. In this blog post, we will walk you through the process of creating a real-time chat app using React. This react chat application will include features such as sending messages, receiving messages, and real-time updates. We will also discuss how to create a user-friendly interface and manage the state of the application using React hooks.
To start building our chat app, we first need to set up the react app. To do this, we will use the create-react-app command. This command creates a new React app with a basic file structure and some starting files.
1npx create-react-app chat-app 2
After running this command, navigate into the newly created project folder.
1cd chat-app 2
Now, we have a new React application ready to be developed. The entry point of our application is the App.js file. This is where we will start building our chat app.
The user interface of our chat app will consist of two main parts: the chat room and the messages component. The chat room will display the active users and the messages component will display the chat messages.
To create these components, we will first import React and then define a function component.
1import React from 'react'; 2 3function App() { 4 return ( 5 <div className="App"> 6 // Our components will go here 7 </div> 8 ); 9} 10 11export default App; 12
In the following sections, we will dive deeper into how to create these components and how to manage their state.
Real-time communication is a crucial part of any chat application. In our React chat app, we will use web sockets for real-time communication. Web sockets allow for two-way communication between the server and the client, making it perfect for our needs.
To implement web sockets, we will use the socket.io library. First, install it using the following command:
1npm install socket.io-client 2
Then, in our App.js file, import the io function from the socket.io-client package and establish a connection with the server.
1import { io } from "socket.io-client"; 2 3const socket = io('http://localhost:3000'); 4
Now, we have a real-time connection between our client and server, ready to send and receive messages.
The chat room is where users will interact with each other. It will display a list of active users and the messages they send. To create the chat room, we will create a new file called ChatRoom.js in our components folder.
1import React from 'react'; 2 3function ChatRoom() { 4 return ( 5 <div className="chat-room"> 6 // The chat room components will go here 7 </div> 8 ); 9} 10 11export default ChatRoom; 12
In this component, we will manage the state of the active users and the messages using React hooks. We will also listen for any new messages from the server and update the state accordingly.
The chat message component will display a single message in the chat room. It will show the user's name, the message text, and the time the message was sent. To create this component, we will create a new file called ChatMessage.js in our components folder.
1import React from 'react'; 2 3function ChatMessage({ message }) { 4 return ( 5 <div className="chat-message"> 6 <p>{message.user}: {message.text}</p> 7 </div> 8 ); 9} 10 11export default ChatMessage; 12
In this component, we are receiving the message object as a prop and displaying its user and text properties. We will use this component in our chat room to display all the messages.
React hooks are a powerful feature of React that allow us to manage state and side effects in function components. In our chat app, we will use the useState and useEffect hooks to manage the state of our active users and messages, and to listen for new messages from the server.
1import React, { useState, useEffect } from 'react'; 2 3function ChatRoom() { 4 const [messages, setMessages] = useState([]); 5 const [users, setUsers] = useState([]); 6 7 // More code will go here 8 9 return ( 10 <div className="chat-room"> 11 // The chat room components will go here 12 </div> 13 ); 14} 15 16export default ChatRoom; 17
In this code, we are initializing our state with an empty array for both messages and users. We will update these states when we receive new data from the server.
Sending and receiving messages is the core functionality of our chat app. To send a message, we will emit a 'message' event to the server with the message text. To receive messages, we will listen for 'message' events from the server and update our messages state.
1import React, { useState, useEffect } from 'react'; 2import { io } from "socket.io-client"; 3 4const socket = io('http://localhost:3000'); 5 6function ChatRoom() { 7 const [messages, setMessages] = useState([]); 8 const [messageText, setMessageText] = useState(''); 9 10 // Send a message 11 const sendMessage = () => { 12 socket.emit('message', messageText); 13 setMessageText(''); 14 }; 15 16 // Receive messages 17 useEffect(() => { 18 socket.on('message', (message) => { 19 setMessages(messages => [...messages, message]); 20 }); 21 }, []); 22 23 // More code will go here 24 25 return ( 26 <div className="chat-room"> 27 // The chat room components will go here 28 </div> 29 ); 30} 31 32export default ChatRoom; 33
In this code, we are sending a message when the sendMessage function is called. We are also listening for 'message' events from the server and updating our messages state with the new message.
User interactions are a crucial part of any chat app. In our React chat app, we will handle user interactions such as joining a chat room, sending a message, and leaving a chat room.
To join a chat room, we will emit a 'join' event to the server with the user's details. To leave a chat room, we will emit a 'leave' event. To send a message, we will use the sendMessage function we defined earlier.
1import React, { useState, useEffect } from 'react'; 2import { io } from "socket.io-client"; 3 4const socket = io('http://localhost:3000'); 5 6function ChatRoom() { 7 const [messages, setMessages] = useState([]); 8 const [messageText, setMessageText] = useState(''); 9 const [user, setUser] = useState(null); 10 11 // Join a chat room 12 const joinChatRoom = (userDetails) => { 13 setUser(userDetails); 14 socket.emit('join', userDetails); 15 }; 16 17 // Leave a chat room 18 const leaveChatRoom = () => { 19 socket.emit('leave', user); 20 setUser(null); 21 }; 22 23 // More code will go here 24 25 return ( 26 <div className="chat-room"> 27 // The chat room components will go here 28 </div> 29 ); 30} 31 32export default ChatRoom; 33
In this code, we are handling user interactions with the chat room. We are allowing users to join and leave the chat room and to send messages.
React Router DOM is a powerful routing library for React. It allows us to create multiple routes in our application and to navigate between them. In our chat app, we will use React Router DOM to create routes for the home page, the chat room, and the user profile page.
First, install React Router DOM using the following command:
1npm install react-router-dom 2
Then, in our App.js file, import the BrowserRouter, Route, and Switch components from react-router-dom and define our routes.
1import React from 'react'; 2import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; 3import HomePage from './components/HomePage'; 4import ChatRoom from './components/ChatRoom'; 5import UserProfile from './components/UserProfile'; 6 7function App() { 8 return ( 9 <Router> 10 <Switch> 11 <Route path="/" exact component={HomePage} /> 12 <Route path="/chat" component={ChatRoom} /> 13 <Route path="/profile" component={UserProfile} /> 14 </Switch> 15 </Router> 16 ); 17} 18 19export default App; 20
In this code, we are defining three routes: the home page at the / path, the chat room at the /chat path, and the user profile page at the /profile path.
Styling is an important part of any web app. It improves the user experience and makes the app more appealing. In our chat app, we will use CSS to style our components.
First, create a new file called App.css in the src folder. Then, import this file in our App.js file.
1import React from 'react'; 2import './App.css'; 3 4// More code will go here 5 6export default App; 7
In the App.css file, we can define our styles. For example, we can set the background color of the chat room, the font size of the messages, and the layout of the user list.
1.chat-room { 2 background-color: #f5f5f5; 3 display: flex; 4 flex-direction: column; 5 padding: 20px; 6} 7 8.chat-message { 9 font-size: 16px; 10 margin-bottom: 10px; 11} 12 13.user-list { 14 display: flex; 15 flex-direction: column; 16 margin-top: 20px; 17} 18
In this code, we are styling the chat room, the chat messages, and the user list. We are setting the background color of the chat room, the font size of the messages, and the layout of the user list.
User authentication is an important feature of any chat app. It allows users to have private conversations and to have a personalized experience. In our React chat app, we will add user authentication using Firebase.
First, install Firebase using the following command:
1npm install firebase 2
Then, in our App.js file, import Firebase and initialize it with your Firebase configuration.
1import React from 'react'; 2import firebase from 'firebase/app'; 3import 'firebase/auth'; 4 5const firebaseConfig = { 6 // Your Firebase configuration goes here 7}; 8 9firebase.initializeApp(firebaseConfig); 10 11// More code will go here 12 13export default App; 14
Now, we can use Firebase's authentication methods to sign in and sign out users. We can also get the current user's details using firebase.auth().currentUser.
Saving chat messages in local storage allows users to see their previous messages even after refreshing the page. In our React chat app, we will save chat messages in local storage using the localStorage API.
First, in our ChatRoom component, we will save the messages in local storage every time the messages state changes.
1useEffect(() => { 2 localStorage.setItem('messages', JSON.stringify(messages)); 3}, [messages]); 4
Then, when initializing the messages state, we will get the messages from local storage.
1const [messages, setMessages] = useState( 2 JSON.parse(localStorage.getItem('messages')) || [] 3); 4
Now, whenever a user sends or receives a message, it will be saved in local storage. When the user refreshes the page, the messages will be loaded from local storage.
Once our chat app is complete, we can deploy it to the web. We will use Firebase Hosting for deployment because it is free, easy to use, and integrates well with our Firebase authentication.
First, install the Firebase CLI using the following command:
1npm install -g firebase-tools 2
Then, in the root directory of your project, run the following command to log in to Firebase:
1firebase login 2
Next, initialize your project with Firebase using the following command:
1firebase init 2
Finally, deploy your project to Firebase using the following command:
1firebase deploy 2
Now, your React chat app is live on the web!
Testing is an important part of software development. It ensures that our code works as expected and helps us catch bugs before they reach the users. In our React chat app, we can use the Jest testing library to write tests for our components and functions.
First, install Jest using the following command:
1npm install --save-dev jest 2
Then, create a new file with the .test.js extension for each component or function you want to test. In these files, write your tests using the test function from Jest.
1import { render, screen } from '@testing-library/react'; 2import App from './App'; 3 4test('renders learn react link', () => { 5 render(<App />); 6 const linkElement = screen.getByText(/learn react/i); 7 expect(linkElement).toBeInTheDocument(); 8}); 9
In this code, we are testing that the App component renders a link with the text "learn react". We can run our tests using the npm test command.
In this blog post, we have seen how we can use React to build a real-time chat app. We have covered many topics, including setting up a React app, creating a user interface, implementing real-time communication with web sockets, managing state with React hooks, handling user interactions, routing with React Router DOM, styling with CSS, adding user authentication with Firebase, saving chat messages in local storage, deploying with Firebase Hosting, and testing with Jest.
React is a powerful library for building user interfaces, and it shines in applications like chat apps where the state changes frequently and in real-time. With its component-based architecture, React allows us to write clean, modular, and reusable code, making our development process more efficient and our codebase easier to maintain.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.