Skip to content

Instantly share code, notes, and snippets.

@BrianLitwin
Last active February 6, 2019 16:22
Show Gist options
  • Save BrianLitwin/5de600679150535c50b66da5bf68b9f7 to your computer and use it in GitHub Desktop.
Save BrianLitwin/5de600679150535c50b66da5bf68b9f7 to your computer and use it in GitHub Desktop.

This form has the default HTML form behavior of browsing to a new page when the user submits the form. It's convenient to have a JavaScript function that handles the submission of the form and has access to the data that the user entered in the form. In React, you do this w/ 'Controlled Components'

Controlled Components

In HTML, form elements such as , <textarea>, and typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components and only updated with 'setState()'. We can combine the two by making the React state the single 'source of truth'. Then the React component that renders the form also controls what happens on subsequent user input. An input form element whose value is controlled by React in this way is called a 'controlled component' Example: Form Label There's three areas you need to address in a 'controlled component' the form's 'onSubmit' function the elements 'onChange' function the elements 'value' The typical cycle is to pass in the 'value', pass in a function to update the component's state in onChange so that the 'value' will update when the user enters information, and pass in a function to update the state when the user clicks a button to submit the Form. With a controlled component, every state mutation will have a handler function. this makes it straightforward to modify or validate user input. <textarea type='text'>, , and all accept a value attribute that you can use to implement a controled component. If you've specified a value but the input is still editable, the value may be 'null' or 'undefined'

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