You have probably written HTML forms before, and so the structure below resonates with you. Perhaps you even smile because, this one, you understand.
Submit 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 onChange property will then fire when the user enters text into the textfield. Doing this tiggers the setName function which sets the name value to whatever the user enters. That value becomes the new name which is tied to the textfield's value, hence the value changes to reflect the user's input That is the whole flow of Controlled Inputs . This is how React controls inputs. Handling Form Submission function Form () { const [ name , setName ] = useState ( "" ); function handleSubmit ( event ) { event . preventDefault (); console . log ( name ); } return ( < form onSubmit = { handleSubmit } > < input type = " text " value = { name } onChange = {( event ) => setName ( event . target . value )} / > < button type = " submit " > Submit < /button > < /form > ); } This is a complete implementation of a form implementation in React. We have already gone through the input flow. Now we have just wrapped the whole element inside a form and added a submit button. Notice there is a function we have added handleSubmit(event){} This function will be executed when the submit button is pressed. Like we have mentioned before, the normal execution flow of forms is such that, the whole page will reload and the form content will be lost. Suppose you want to manipulate or manage the form before submission, then you add the event.preventDefault() line. This stops the default workflow of form submission such that the page won't reload and your changes won't be lost. The event property is passed automatically into the handleSubmit function. But ... What if you have more fields? Sure, you can have more than one state variables e.g. const [ name , setName ] = useState ( "" ); const [ email , setEmail ] = useState ( "" ); const [ password , setPassword ] = useState ( "" ); This still works, but notice that we have repeated the useState. Of course optimization may not be the first thing to think about as a newbie, but once you get the hang of things, consider doing this instead: const [ formData , setFormData ] = useState ({ name : "" , email : "" , password : "" }) Here we have compressed the definition to only have one useState, making our code more concise. Input Types Just like in HTML, we have different types on inputs and their implementation follow the same logic but with a few minor tweaks: Checkbox const [ agreed , setAgreed ] = useState ( false ); < input type = " checkbox " checked = { agreed } onChange = {( event ) => setAgreed ( event . target . checked )} / > Here we use event.target.checked instead of event.target.value Select < select value = { country } onChange = {( event ) => setCountry ( event . target . value )} > < option value = "" > Select a country < /option > < option value = " kenya " > Kenya < /option > < option value = " uganda " > Uganda < /option > < /select > Textarea < textarea value = { message } onChange = {( event ) => setMessage ( event . target . value )} / > Form Validation For forms to be complete, validation must be enforced to ensure correct and proper data has been entered. The basic validation we know is that a form shouldn't be submitted with empty data or fields. That is exactly where validation comes in. An example of validation in the handleSubmit function is as follows: const [ error , setError ] = useState ( "" ); function handleSubmit ( event ) { event . preventDefault (); if ( ! formData . name . trim ()) { setError ( " Name is required " ); return ; } if ( ! formData . email . includes ( " @ " )) { setError ( " Enter a valid email " ); return ; } console . log ( formData ); } And with that, you have the basics to build a react form and implement validation. Practice more until you grasp it all. Exercise Build the form as below and implement everything we have gone through. If you get stuck, refer or engage in the comments. ┌─────────────────────────┐ │ Create an account │ │ │ │ Name │ │ [] │ │ │ │ Email │ │ [] │ │ │ │ Password │ │ [____________________] │ │ │ │ ☑ I agree to the terms │ │ │ │ [ Create Account ] │ └─────────────────────────┘ This will test your knowledge on : useState Controlled inputs onChange onSubmit preventDefault Multiple fields Checkbox handling Validation Error messages Conclusion We gone through forms which are the bulding blocks of react state-ful-ness. Keep practicing, see you in the next one
Forms in React : From Inputs to Controlled Components
Silas

