I am trying to learn React basics and completed a chat app. My main purpose was to create user-specific text areas and preserve the draft when changing between people. Beforehand I had some trouble with the ContactList and posted it on StackOverflow. Thankfully it got solved and I finished this assignment. I don't know if the code is any good, what can I do to improve it and are there any logical mistakes? I only used React documentation and Stack Overflow to get help. This is my first solo project so I am open to any improvements and suggestions.
//App.jsx
import { useState } from 'react'
import ContactList from './ContactList';
import './App.css'
import Chat from './Chat';
export default function App() {
const [selectedContact, setSelectedContact] = useState(() => contacts[0]);
const [messages, setMessages] = useState({
0:"",
1:"",
2:"",
})
function handleTextChange(e){
setMessages({
...messages,
[selectedContact.id]: e.target.value
})
}
function handleButtonClick(contact , event){
event.preventDefault();
setSelectedContact(contact);
}
return (
<div className='container'>
<ContactList handleButtonClick={handleButtonClick} contacts={contacts} />
<Chat contact={selectedContact} handleTextChange={handleTextChange} messages={messages}/>
</div>
)
}
const contacts = [
{id: 0, name: 'Taylor', email: '[email protected]'},
{id: 1, name: 'Alice', email: '[email protected]'},
{id: 2, name: 'Bob', email: '[email protected]'},
];
// Chat.jsx
export default function Chat({ contact, handleTextChange, messages }) {
return (
<div className="input-area">
<textarea
className="text-area"
placeholder={"Chat to " + contact.name}
value={messages[contact.id]}
onChange={handleTextChange}
></textarea>
<button key={contact.id} className="personName">
Send to {contact.email}
</button>
</div>
);
}
//ContactList.jsx
export default function ContactList({ handleButtonClick, contacts }) {
return (
<div className="contact-buttons">
{contacts.map((contact) => {
return (
<button
key={contact.id}
className="personName"
onClick={(event) => handleButtonClick(contact , event)}
>
{contact.name}
</button>
);
})}
</div>
);
}