importReact,{useState,useEffect}from'react';import'./App.css'functionApp(){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"}])},[]);consthandleNameInputChange=(event)=>{constinputValue=event.currentTarget.value;updateNewName(inputValue);}consthandleEmailInputChange=(event)=>{constinputValue=event.currentTarget.value;updateNewEmail(inputValue);}consthandleFormSubmit=(event)=>{event.preventDefault();//prevent page refreshconstnewUser={name:newName,email:newEmail,}updateUsers([...users,newUser]);}return(<divclassName="App"><h1>App.js</h1><div><formclassName="user-add-form"onSubmit={(event)=>{handleFormSubmit(event)}}><labelhtmlFor="name">Name:</label><inputtype="text"name="name"onChange={(event)=>{handleNameInputChange(event)}}/><labelhtmlFor="emai">Email:</label><inputtype="email"name="email"onChange={(event)=>{handleEmailInputChange(event)}}/><inputtype="submit"value="Add New User!"/></form></div><br/><buttononClick={()=>{console.log(users)}}>Log users to console!</button><div>{users.map((user,index)=>{return(<divkey={user.email}><br/><div><span>{index+1}. </span><span>{user.name}</span></div><div><span>{user.email}</span></div></div>)})}</div></div>);}exportdefaultApp;
Top comments (0)