02.15 React State - User List in one component (class components)
adriangheo
Posted on October 26, 2022
src/App.js
import React from 'react';
import './App.css'
class App extends React.Component{
constructor(){
super();
this.state = {
users: [],
newUserName: '',
newUserEmail: '',
}
}
//we use componentDidMount for the side effect
//...of populating the initial component state
componentDidMount(){
this.setState({ users: [
{
name: "Jane Doe",
email: "jane.doe@gmail.com"
},
{
name: "Joe Shmoe",
email: "joe.shmoe@gmail.com"
}
]})
}
handleNameInputChange(event){
const inputValue = event.currentTarget.value;
this.setState({newUserName: inputValue})
}
handleEmailInputChange(event){
const inputValue = event.currentTarget.value;
this.setState({newUserEmail: inputValue})
}
handleFormSubmit(event){
event.preventDefault(); //prevent page refresh
const newUser = {
name: this.state.newUserName,
email: this.state.newUserEmail,
}
this.updateUsersList(newUser);
}
updateUsersList =(newUser) => {
this.setState((previousState)=>{
return {users: [
...previousState.users,
newUser
]}
});
}
render(){
return (
<div className="App" >
<h1>App.js</h1>
<div>
<form className="user-add-form" onSubmit={(event)=>{this.handleFormSubmit(event)}} >
<label htmlFor="name">Name:</label>
<input
type="text"
name="name"
onChange={(event)=>{this.handleNameInputChange(event)}}
/>
<label htmlFor="emai">Email:</label>
<input
type="email"
name="email"
onChange={(event)=>{this.handleEmailInputChange(event)}}
/>
<input type="submit" value="Add New User!"/>
</form>
</div>
<br/>
<button onClick={()=>{console.log(this.state.users)}}>Log users to console!</button>
<div>
{
this.state.users.map((user, index) => {
return(
//note: react uses keys as a way to identify an element of the same type among its siblings during re-renders
<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;
src/App.css
.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