Forms in React : From Inputs to Controlled Components
You have probably written HTML forms before, and so the structure below resonates with you. Perhaps you even smile because, this one, you understand. <form> <input type= "text" /> <button> Submit </button> </form> If you have done this, you know what happens when you click the button. The whole form reloads, the changes or inputs are cleared. This is the default behavior of forms in HTML. In React, we handle every step and every stage so that we have control over the data and the behavior of the form and data. The above signature represents what we call UNCONTROLLED INPUT . This means that there isn't a single source of truth to the value of this field, hence it can change to anything, and any value In addition to the above attributes, we will add value and onChange props to the input element as below: <input type= "text" value= {} onChange= {}/ > value represents the content of the input field e.g. the name text that the user enters in a Name field. onChange is the function that will be triggered everytime the input changes. Whenever a key is pressed within this field, this function will be invoked. Controlled inputs have their values set and manipulated by states, as we saw in Part 1 of the series. Uncontrolled inputs on the other hand do not have a manager that will dictate what goes into the field and when. Now let's write our first React Input, we'll keep it simple. import { useState } from " react " function Form (){ const [ name , setName ] = useState ( "" ) return ( < input type = " text " value = { name } onChange = {( event ) => setName ( event . target . value )} / > ) Let's look at what happens in the above. We have declared a state [name,setName] . name is the state variable setName is a function used to update the variable We then initialized an input element with properties value and onChange Note that, when the value of an input is set, that will always be the value even if you type something into the box. That is the essence of controlled input. The