Untitled
unknown
plain_text
a year ago
3.6 kB
9
Indexable
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',
cursor: 'pointer'
},
errorText: {
color: 'red'
}
}
}
const PhoneBookForm = ({ addEntryToPhoneBook }) => {
const [entry, setEntry] = useState({firstName: "Coder", lastName: "Byte", phone: "8885559999"});
const [hasError, setHasError] = useState(false);
return (
<form onSubmit={e => {
e.preventDefault();
if (entry.firstName && entry.lastName && entry.phone) {
addEntryToPhoneBook(entry);
setEntry({});
setHasError(false);
} else {
setHasError(true);
}
}}
style={style.form.container}>
<label>First name:</label>
<br />
<input
style={style.form.inputs}
className='userFirstname'
name='userFirstname'
type='text'
value={entry.firstName ?? ''}
onChange={(e) => {setEntry({...entry, firstName: e.target.value}); setHasError(false);}}
/>
<br/>
<label>Last name:</label>
<br />
<input
style={style.form.inputs}
className='userLastname'
name='userLastname'
type='text'
value={entry.lastName ?? ''}
onChange={(e) => {setEntry({...entry, lastName: e.target.value}); setHasError(false);}}
/>
<br />
<label>Phone:</label>
<br />
<input
style={style.form.inputs}
className='userPhone'
name='userPhone'
type='text'
value={entry.phone ?? ''}
onChange={(e) => {setEntry({...entry, phone: e.target.value}); setHasError(false);}}
/>
<br/>
<input
style={style.form.submitBtn}
className='submitButton'
type='submit'
value='Add User'
/>
{hasError ?
<>
<br/>
<p style={style.form.errorText}>All fields must be filled out</p>
</> : null
}
</form>
)
}
const InformationTable = ({entries}) => {
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>
{entries.sort((a,b) => a.lastName?.localeCompare(b.lastName)).map((entry, index) => {
const {firstName, lastName, phone} = entry;
return <tr key={JSON.stringify({entry, index})}>
<td>{firstName}</td>
<td>{lastName}</td>
<td>{phone}</td>
</tr>
})}
</table>
);
}
const Application = (props) => {
const [entries, setEntries] = useState([]);
const addEntry = (entry) => setEntries([...entries, entry]);
return (
<div>
<PhoneBookForm addEntryToPhoneBook={addEntry} />
<InformationTable entries={entries} />
</div>
);
}
const container = document.getElementById('root');
const root = createRoot(container);
root.render(<Application />);Editor is loading...
Leave a Comment