Skip to content

Instantly share code, notes, and snippets.

@denefi
Forked from luisjunco/m3-react-forms.md
Created April 5, 2023 11:04
Show Gist options
  • Save denefi/80c010369ce16eadc694a21a2864ca1f to your computer and use it in GitHub Desktop.
Save denefi/80c010369ce16eadc694a21a2864ca1f to your computer and use it in GitHub Desktop.
React Controlled Components - Cheatsheet

React Controlled Components

Intro (what are controlled components & why we use them)

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

  • In React, mutable state is typically kept in the state of components. And when that state needs to change, we go through React (ie. we tell React to update state)

  • 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, a controlled component is a component where we have a form + we store the state of the fields in React 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)

3.1. Create a stateful variable (for each field)

const [title, setTitle] = useState("");

3.2. Read the input value from state

<input ..... value={title} />

3.3 Add onChange event (and update state with the new value)

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

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

    const handleSubmit = (e) => {
      e.preventDefault();
    
      // 
      //this is where your magic happens
      // 
      
      //clear form
      setTitle("");
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment