Controlled components - KatyaHorton/Udacity-React-practice GitHub Wiki

Controlled components, basics

Forms state typically live inside of a DOM, but React has Controlled components!

Controlled components: components which render a form, but the source of truth for that form state lays inside of the component state, rather than inside of the DOM.

Controlled components - because React controlling the state of the form.

Component which renders a form of a single input element:

class NameForm extends React.Component {
 state = {
  email: ''
 }
 render() {
  return(
   <form> 
    <input type='text' value='this.state.email'>
   </form>
)}}

The fact that the value attribute of the input is set to this.state.email means:

  • text in the input field will be whatever the email property of our component state is;
  • only way to update thestate in the input filed is to update the email property of the component state;
  • React is in control of the email property of the state, right?
  • there for it is a Controlled Component

To change the input field to change, we can create the handleChange() method, that uses setState() to update the email address.

class NameForm extends React.Component {
 state = { email: '' }
//method that will update the email address using setState method
 handleChange = (event) => {
  this.setState({ email: event.target.value })
}

 render() {
  return(
   <form>
//whenever the input field is changed we can call handleChange method by passing it to the onChange attribute
    <input 
      type='text' 
      value={this.state.email}
      onChange={this.handleChange} />
  
   </form>
)}}

Benefits of Controlled Components:

  • instant input validation
  • conditionally enable/disable buttons (form buttons)
  • enforce input formats

Heart of React is in Controlled Components - updating UI based on user's input!

State changes - UI updates.
⚠️ **GitHub.com Fallback** ⚠️