02.16 React State - User List in one component (functional components)
adriangheo
Posted on October 26, 2022
import React, { useState, useEffect} from 'react';
import './App.css'
function App () {
const [users, updateUsers] = useState([]);
const [newName, updateNewName] = useState('');
const [newEmail, updateNewEmail] = useState('');
const [newUser, updateNewUserl] = useState({});
useEffect(() => {
//simillar to componentDidMount, we useEffect() hook
//... for the side effect of populating the initial component state
//... and by adding an empty array ([]) as a second argument,
//... we make sure to run this effect only once (on mount )
updateUsers( [
{
name: "Jane Doe",
email: "jane.doe@gmail.com"
},
{
name: "Joe Shmoe",
email: "joe.shmoe@gmail.com"
}
])
}, []);
const handleNameInputChange = (event) => {
const inputValue = event.currentTarget.value;
updateNewName(inputValue);
}
const handleEmailInputChange = (event) => {
const inputValue = event.currentTarget.value;
updateNewEmail(inputValue);
}
const handleFormSubmit = (event) => {
event.preventDefault(); //prevent page refresh
const newUser = {
name: newName,
email: newEmail,
}
updateUsers([...users, newUser]);
}
return (
<div className="App" >
<h1>App.js</h1>
<div>
<form className="user-add-form" onSubmit={(event)=>{handleFormSubmit(event)}} >
<label htmlFor="name">Name:</label>
<input
type="text"
name="name"
onChange={(event)=>{handleNameInputChange(event)}}
/>
<label htmlFor="emai">Email:</label>
<input
type="email"
name="email"
onChange={(event)=>{handleEmailInputChange(event)}}
/>
<input type="submit" value="Add New User!"/>
</form>
</div>
<br/>
<button onClick={()=>{console.log(users)}}>Log users to console!</button>
<div>
{
users.map((user, index) => {
return(
<div key={user.email}>
<br/>
<div><span>{index +1 }. </span><span>{user.name}</span></div>
<div><span>{user.email}</span></div>
</div>
)
})
}
</div>
</div>
);
}
export default App;
.App{
background-color: lightskyblue;
padding: 20px 10px;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
π πͺ π
π©
adriangheo
Posted on October 26, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript Mastering React Performance: In-Depth Guide to useCallback and useMemo. π
November 24, 2023
javascript Rewrite styled-components in ReactJS with just 60 lines of JavaScript code
September 29, 2023