Form validation in react

Manage the error by using the if-else statement in the sandbox. Utilize the error handling codes and example provided in the react-use-form to handle errors. Upon callback, the field will be added to the “fields” state property which will be used for iteration during form submission. The controls that feature an “isValid” method will be requested to validate.


Solution:

The question you asked caught my attention. Although I haven’t encountered a similar issue before, it’s a valid concern. Upon experimenting with React, I discovered a solution that doesn’t require iterating through refs or children (except during validation).

To avoid repetition, I utilized react component wrappers on each form field and a react element for the form itself. Upon rendering, the form react component duplicates each child with an additional property called

onComponentMounted

. This property is invoked by the form fields upon mounting. After this step, the process becomes straightforward. The

onComponentMounted

callback will append the field to a “fields” state property. This property will be looped over when the form is submitted. Controls that provide an “isValid” method will be requested to validate.

With this method, it becomes effortless to create forms such as the one below.

React.render(
        
        
        
        
        
        , document.getElementById('form1'));

The complete code can be accessed at http://jsfiddle.net/6tjz2b6r/. While only TextField is currently supported, additional control types can be effortlessly incorporated.

Frequently Asked Questions