Skip to content

Instantly share code, notes, and snippets.

@luisjunco
Last active February 9, 2024 06:25
Show Gist options
  • Save luisjunco/6c59bc3ea6a1d0b3a975d15ff2115fec to your computer and use it in GitHub Desktop.
Save luisjunco/6c59bc3ea6a1d0b3a975d15ff2115fec to your computer and use it in GitHub Desktop.
React Forms - Cheatsheet

React Forms

Intro

  • Form elements such as <input>, <textarea>, and <select> naturally keep some internal state (and change based on user's input).

  • From the React team:

    In most cases, we recommend using controlled components to implement forms. In a controlled component, form data is handled by a React component.

  • In short: when you work with froms, you usually want to store the info from the form in "State".

Steps to create a Controlled Component

  1. Create the form in your JSX:

    <form>
      <input type="text" name="title" placeholder="enter the title" />
      <button>Create</button>
    </form>
  2. Add an onSubmitevent & prevent form submission:

    const handleSubmit = (e) => {
      e.preventDefault();
    }  
    <form onSubmit={handleSubmit}>
  3. Make it a "Controlled Component" (we will store the data in state + read the data from state)

    1. Create a stateful variable (for each field)

      const [title, setTitle] = useState("");
    2. Read the input value from state

      <input ..... value={title} />
    3. Add onChange event (and update state with the new value)

      <input ..... onChange={(e) => { setTitle(e.target.value) }} />
  4. Handle form submission

    const handleSubmit = (e) => {
      e.preventDefault();
    
      // 
      //this is where your magic happens
      // 
      
    }
  5. (optional) clear form upon submission

    const handleSubmit = (e) => {
      e.preventDefault();
    
      // 
      //this is where your magic happens
      // 
      
      //clear form
      setTitle("");
    }
@luisjunco
Copy link
Author

luisjunco commented Jul 27, 2022

For forms with a lot of fields....

  • When you have many fields in a form, it can be annoying to create one stateful variable for each form field.
  • In those cases, it is also possible to use a different pattern: creating only one stateful variable (an object) for all form fields.
  • You can see that pattern here: https://stackoverflow.com/a/67234242/11298742

Main ideas:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment