React js form input component

Building reusable form input component with error handling in React Hooks

Avani Bataviya

--

Are you not sure how to make a reusable component in a react ? Are you still avoiding react hooks in common components ? If one of the above questions is suitable to you then this article for you.

What’s the reusable component?

Reusable component is the simple pieces of code that is used multiple times in your application. For example, we can use the same form input in email, password or as text filed by passing different types in component. So up to end logic must be generic and simple that full fill our requirements.

In this article I have used reactstrap for design and you will come to know how to make common form input component and essay way to handle errors of the same.

How does it work?

The Component will

  • Accept name, default value, type(i.e email, password or text) and onChange function from another component(i.e. Form),
  • Render component based on given props.
  • Call local onChangeHandler, process data and return final value
  • Call validationHandler to validate input value and pass error to form (it’s optional)

Basic custom input component,

How to Use it ?

Now what if we want to validate data. For instance

  • Value must be minimum some characters (i.e. 6) long
  • Value must be maximum 8 characters long
  • Value must be 5 characters,
  • Value must be follow some regular expression

To full fill above requirement must have to validate input value and if value not follow given rule, show error message to user. You can validate value in on Blur or on Change of input as per your choice and requirement. So here i have added onValidationChange method to validate value on blur of input. Pass method like this, onBlur={onValidationChange}

Lest’s have look on final code of common component …

Full Code of react form input common component.

To make input’s value required use isRequired, add maxLength or minLength for restrict number of character in input or you can validate value by any regular expression. Here you can see email example.

Now user click in input and type something then on blur of input we are validating it’s value but what is user will not touch input and direct submit form then how we will handle errors? Validate form input value before form will submit.

Checkout full code on GitHub, https://github.com/AvaniBataviya/react-common-component/blob/master/src/App.js

That’s it.

Full code you can find on GitHub repository: https://github.com/AvaniBataviya/react-common-component

You can modify components as per your requirements too. Happy Coding!!!

--

--