Skip to content
This repository has been archived by the owner on Jul 10, 2020. It is now read-only.

Latest commit

 

History

History
59 lines (48 loc) · 2.26 KB

21-react-controlling-form-values-with-react-4627dd2d.md

File metadata and controls

59 lines (48 loc) · 2.26 KB

21 Controlling Form Values with React

Notes

  • There are many situations where you want to programmatically control the value of a form field.
  • Maybe you want to set the value of one field based on the user’s interactions with another element. Or maybe you want to change the user’s input as they’re typing it.
  • In this example, we’ll be preventing the user from typing upper case characters into our field by turning our input from an “Uncontrolled field” to a “Controlled field.”
<body>
  <div id="root"></div>
  <script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
  <script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/[email protected]/babel.js"></script>
  <script type="text/babel">
    function UsernameForm() {
      const [username, setUsername] = React.useState('');

      function handleSubmit(event) {
        event.preventDefault();
        alert(`You entered: ${username}`);
      }

      function handleChange(event) {
        // making sure that the value is turned into lower case
        // the input value is now handled with React
        setUsername(event.target.value.toLowerCase());
      }

      return (
        <form onSubmit={handleSubmit}>
          <div>
            <label htmlFor="usernameInput">Username:</label>
            {/* controlling the value with value={username} */}
            <input
              id="usernameInput"
              type="text"
              onChange={handleChange}
              value={username}
            />
          </div>
          <button type="submit">Submit</button>
        </form>
      );
    }

    ReactDOM.render(<UsernameForm />, document.getElementById('root'));
  </script>
</body>

Additional resource