Chat Application

Step 1: Set Up Your React Project

Open your terminal and run the following commands:

npx create-react-app chat-app
cd chat-app

Step 2: Create Chat Application Components

Replace the content of src/App.js with the following code:

import React, { useState } from 'react';
import './App.css';

const App = () => {
  const [messages, setMessages] = useState([]);
  const [message, setMessage] = useState('');
  const [username, setUsername] = useState('');

  const handleSendMessage = () => {
if (message && username) {
  setMessages([...messages, { username, text: message }]);
  setMessage('');
}
}; return (
<div className="App">
  <h1>Chat Application</h1>
  <div className="chat-window">
    <div className="messages">
      {messages.map((msg, index) => (
        <div key={index} className="message">
          <strong>{msg.username}: </strong>
          {msg.text}
        </div>
      ))}
    </div>
  </div>
  <input
    type="text"
    placeholder="Your name"
    value={username}
    onChange={(e) => setUsername(e.target.value)}
  />
  <input
    type="text"
    placeholder="Type a message"
    value={message}
    onChange={(e) => setMessage(e.target.value)}
  />
  <button onClick={handleSendMessage}>Send</button>
</div>
); }; export default App;

Step 3: Style Your Chat Application

Open src/App.css and add the following styles:

body {
  margin: 0;
  font-family: Arial, sans-serif;
}

.App {
  text-align: center;
  padding: 20px;
}

.chat-window {
  border: 1px solid #ccc;
  padding: 10px;
  height: 300px;
  overflow-y: scroll;
  margin-bottom: 20px;
}

.messages {
  text-align: left;
}

.message {
  margin: 5px 0;
}

input {
  padding: 10px;
  margin-right: 10px;
  width: 200px;
}

button {
  padding: 10px;
}

Step 4: Run Your Application

In the terminal, run:

npm start

Comments

Leave a Reply

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