import React, { useState } from 'react';
import { createRoot } from 'react-dom/client';
const style = {
table: {
borderCollapse: 'collapse'
},
tableCell: {
border: '1px solid gray',
margin: 0,
padding: '5px 10px',
width: 'max-content',
minWidth: '150px'
},
form: {
container: {
padding: '20px',
border: '1px solid #F0F8FF',
borderRadius: '15px',
width: 'max-content',
marginBottom: '40px'
},
inputs: {
marginBottom: '5px'
},
submitBtn: {
marginTop: '10px',
padding: '10px 15px',
border: 'none',
backgroundColor: 'lightseagreen',
fontSize: '14px',
borderRadius: '5px'
};
function PhoneBookForm({ addEntryToPhoneBook }) {
const [user, setUser] = useState({
firstName: 'Coder',
lastName: 'Byte',
phone: '8885559999'
});
const handleChange = (e) => {
const { name, value } = e.target;
setUser(prev => ({
...prev,
[name]: value
}));
};
const handleSubmit = (e) => {
e.preventDefault();
if (user.firstName && user.lastName && user.phone) {
addEntryToPhoneBook(user);
setUser({ firstName: 'Coder', lastName: 'Byte', phone: '8885559999' });
};
return (
<form onSubmit={handleSubmit} style={style.form.container}>
<label>First name:</label><br />
<input
style={style.form.inputs}
className='userFirstname'
name='firstName'
type='text'
value={user.firstName}
onChange={handleChange}
/><br />
<label>Last name:</label><br />
<input
style={style.form.inputs}
className='userLastname'
name='lastName'
type='text'
value={user.lastName}
onChange={handleChange}
/><br />
<label>Phone:</label><br />
<input
style={style.form.inputs}
className='userPhone'
name='phone'
type='text'
value={user.phone}
onChange={handleChange}
/><br />
<input
style={style.form.submitBtn}
className='submitButton'
type='submit'
value='Add User'
disabled={!user.firstName || !user.lastName || !user.phone}
/>
</form>
);
function InformationTable(props) {
return (
<table style={style.table} className='informationTable'>
<thead>
<tr>
<th style={style.tableCell}>First name</th>
<th style={style.tableCell}>Last name</th>
<th style={style.tableCell}>Phone</th>
</tr>
</thead>
<tbody>
{props.entries.map((entry, idx) => (
<tr key={idx}>
<td style={style.tableCell}>{entry.firstName}</td>
<td style={style.tableCell}>{entry.lastName}</td>
<td style={style.tableCell}>{entry.phone}</td>
</tr>
))}
</tbody>
</table>
);
function Application(props) {
const [entries, setEntries] = useState([]);
const addEntryToPhoneBook = (entry) => {
const updated = [...entries, entry];
updated.sort((a, b) => a.lastName.localeCompare(b.lastName));
setEntries(updated);
};
return (
<section>
<PhoneBookForm addEntryToPhoneBook={addEntryToPhoneBook} />
<InformationTable entries={entries} />
</section>
);
const container = document.getElementById('root');
const root = createRoot(container);
root.render(<Application />);