Controlled vs Uncontrolled components


#1


https://www.codecademy.com/courses/react-102/lessons/react-forms/exercises/update-input-value?action=lesson_resume&link_content_target=interstitial_lesson

Help me to understand what and where is the benefit of using uncontrolled components ( "input" tags for example )?
Why do I have to add ''value={this.state.userInput}'' on an uncontrolled component and make it controlled that way?
If I remove that chunk of code ''value={this.state.userInput}'' the program still works.
What did I miss ?
Thanks


var React = require('react');
var ReactDOM = require('react-dom');

var Input = React.createClass({
  getInitialState: function(){
    return{
      userInput: ''
    }
  },
  handleUserInput: function (e) {
   this.setState({
	    userInput: e.target.value
	  });
  },
  render: function () {
    return (
      <div>
        <input type="text" onChange={this.handleUserInput}  />
        <h1>{this.state.userInput}</h1>
      </div>
    );
  }
});

ReactDOM.render(
	<Input />,
	document.getElementById('app')
);


#2

There's only one problem: you can set this.state.userInput to whatever you want, but won't care. You need to somehow make the 's text responsive to this.state.userInput.
Easy enough! You can control an 's text by setting it's value attribute.

<input type="text" onChange={this.handleUserInput} value={this.state.userInput} />

https://www.google.ca/search?q=Controlled+vs+Uncontrolled+components

In this example, we are accepting the value provided by the user and updating the value prop of the component.
https://facebook.github.io/react/docs/forms.html

Sitepoint video: Introduction to One-Way Data Flow

Sitepoint video: Controlled Components vs. Uncontrolled Components in React.js


#3

Thank you for the answer.
The second Sitepoint video helped me a lot. :slight_smile:


#4

You're welcome. I figured it would.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.