DEV Community

adriangheo
adriangheo

Posted on • Edited on

02.16 React State - User List in one component (functional components)

App preview:
The way the app will look like

Project files:
An image of project file structure


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;
Enter fullscreen mode Exit fullscreen mode

.App{
  background-color: lightskyblue;
  padding: 20px 10px;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)