02.13 React State - Basic form with one input (class components)

adriangheo

adriangheo

Posted on October 24, 2022

02.13 React State - Basic form with one input (class components)

App preview:
Image description

Project files:
An image of project file structure


src/App.js

import React from 'react';
import './App.css';
import NameForm from './NameFormCls';

class App extends React.Component{
  render(){
    return (
      <div className="App">
        <h1>App.js</h1>

        <NameForm/>
      </div>
    );
  }
}

export default App;
Enter fullscreen mode Exit fullscreen mode

src/App.css


.App{
  background-color: lightskyblue;
  padding: 20px 10px;
}
Enter fullscreen mode Exit fullscreen mode


src/NameFormCls.js

import React from "react";
import './NameFormCls.css'

class NameForm extends React.Component {
  constructor(){
    super();
    this.state = {
      users: [],
      newUserName: ""
    }
  }

  handleUsernameInputChange = (event) => {
    this.state.newUserName = event.currentTarget.value;
  }

  handleFormSubmit = (event) => {
    event.preventDefault();
    const newUser = {
      username: this.state.newUserName
    }

    this.updateUsersList(newUser)
  }

  updateUsersList = (newUser) => {
    this.setState((prevState) =>{
      return {
        users: [
          ...prevState.users,
          newUser
        ]
      }

    })
  }

  render() {
    return (
      <div className="name-form">
        <h1>NameFormCls.js</h1>
        <h3>User List:</h3>

        <div>
          <form onSubmit={(event)=>{this.handleFormSubmit(event)}}>
            <label htmlFor="username">New Username:</label>
            <input type="text" name="username" onChange={(event)=>{this.handleUsernameInputChange(event)}}></input>

            <input type="submit" value="Submit form!"></input>
          </form>
        </div>

        <div>
          {
            this.state.users.map((user, index) => {
              return(<div>
                <span>{index+1}. </span><span>{user.username}</span><br/>
              </div>)
            })
          }
        </div>
      </div>
    );
  }
}

export default NameForm;
Enter fullscreen mode Exit fullscreen mode

src/NameFormCls.css

.name-form{
    background-color: lightsalmon;
    padding: 10px 10px;
}
Enter fullscreen mode Exit fullscreen mode
πŸ’– πŸ’ͺ πŸ™… 🚩
adriangheo
adriangheo

Posted on October 24, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related