DEV Community

adriangheo
adriangheo

Posted on

02.14 React State - Basic form with one input (functional components)

App preview:
The way the app will look like

Project files:
An image of project file structure


src/App.js

import './App.css';
import NameForm from './NameFormFn';


function App() {
  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/NameFormFn.js

import React, { useState } from "react";
import './NameFormFn.css'

function NameForm() {
  const [users, updateusers] = useState([]);
  const [name, setName] = useState("");

  const handleSubmit = (event) => {
      event.preventDefault();
      updateusers([...users, { name: name }]);
  }

  return (
    <div className="name-form">
      <h2>NameFormFn.js</h2>
      <form onSubmit={handleSubmit}>
        <label>
          New Username:
          <input
            type="text"
            value={name}
            onChange={e => setName(e.target.value)}
          />
        </label>
        <input type="submit" value="Submit" />
      </form>

      <div>
      {
          users.map((user, index) => {
              return(
                <div  key={index}>
                  <div><span>{index + 1 }. </span><span>{user.name}</span></div>
                </div>
              ) 
          }) 
      }
    </div>


    </div>
  );
}

export default NameForm;
Enter fullscreen mode Exit fullscreen mode

src/NameFormFn.css

.name-form{
    background-color: lightsalmon;
    padding: 10px 10px;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)