Originally published on leanylabs.com.
Handling user inputs is the key to building interactive web applications in React.
Forms are a very common and valuable tool for collecting user information. They can be used for authentication, registration, feedback, or to collect other important information.
In this article, we’ll talk about form validation – verifying user inputs to improve the quality of collected data. First, we’ll implement basic form validation from the ground up. Then we’ll explore Formik, a great library for building smart forms in React.
By the time you’re finished reading, you’ll be able to create forms and validate them easily.
Form Validation in React
React has a large community of developers who create libraries for important features like form validation. There are numerous great libraries for easy form validation in React, so typically, you won’t need to write all the code yourself.
We’re still going to explain how to implement basic form validation in React from scratch. Understanding low-level code can help you make better use of form validation libraries, which follow the same principles but add many great features on top of the basic functionality.
State and controlled components in React
React components often have a state object, which stores essential information (data) to represent the most recent state of the component. React state often contains user inputs, so you can also say that it represents the most recent choices and inputs of the user.
<input> components that get their value from the state are called controlled components.
Any time a user types or deletes something from the field, the
onChange event handler will update the state, and the input field will show the updated value.
Read full article on leanylabs.com