Why are onChange and value attributes needed in Create-a-controlled-input challenge?

Why are onChange and value attributes needed in Create-a-controlled-input challenge?
0

#1

Why, in this challenge and the next, do we do this? I don’t understand to have the value attribute and the onChange handler.


Create-a-controlled-input not working even though solution is correct
#2

This particular challenge does not use a value attribute, but the onChange handler is needed in order to update the state’s input property.


#3

So why, in the next challenge (Create a Controlled Form), is the value attribute required? I don’t understand what use it has?


#4

I have moved your question to it’s own topic, because it needs some attention and thee is no point in replying back and forth on the other user’s thread.

Actually, I misspoke in my first reply. It does have a value attribute in the previous challenge for the same reason it does in the Create a Controlled Form challenge. Input elements have value attributes. These are nothing special or new to React. The value attribute is what holds the current value of the input element at any given time.

React uses a virtual DOM and not the actual DOM to update element’s values and attributes. React needs to know what the current value of that input every time a change is made to it (every time you type a character or delete a character). The onChange attribute represents the onchange event handler and allows you to call this.handleChange which will update a state property named input (could be named anything) when there is a change in the input element. Just like in plain JavaScript, event handlers have access to the event object, you can refer to event.target.value to get the current value of the input element. Since any reference to state properties in the render method need to have the most current value, you refer to this.state.input to display the current value.

This is just the way React works. Instead of you updating the DOM element directly like you would with plain JavaScript, you can instead create properties in the state object and reference them in the component’s render method. This is why changes to the element must always be reflected by updating state (using setState), for React to “know” it needs to actually update the DOM.


#5

Thanks so much for the in depth answer. I think I’ll need to practice some more to fully grasp the concept and will definitely be referencing back to this thread.