New YouTube video!How to use the Capacitor Google Maps plugin with Ionic React

Watch now →
Opens in a new tab

Blog

Blog posts and tutorials about Ionic, Capacitor, Javascript, React and Mobile App Development

← Back

Using React Hook Form to build forms and validation in Ionic React

avatar for Using React Hook Form to build forms and validation in Ionic React

By Alan Montgomery
Let's connect!
 on 7th July 2021 in Forms5 min read

Ionic React Hub Blog - Using React Hook Form to build forms and validation in Ionic React

Building forms and validating them in Ionic and React for that matter, can be simple but sometimes it can prove to be strenuous, especially setting up validation and managing all of your state values. You could build out your own framework for form validation and form building like I have done in the past but a really powerful way to get started on this and save a lot of time is to use React Hook Form.

This is a really handy package which includes a simple custom hook useForm to manage your form input values, and also has a really easy to use validation system which hooks into each input and allows you to specify when and how the validation should trigger.

This also prevents re-renders (if used correctly) in your app as well unlike some vanilla solutions or other packages I've came across before.

Getting started

Installation

To install, simply run the following command inside your Ionic React app; npm install react-hook-form

There are a lot of features of React Hook Form you can avail from, but today we're going to focus on the following;

  • Register
  • Errors (Validation)
  • Submitting

useForm hook

React Hook Form makes it easy to manage all of these by destructing from the above useForm hook.

const Home = () => {

	const { register, handleSubmit, formState: { errors } } = useForm({
		mode: "onTouched",
		reValidateMode: "onChange"
	});
...

Notice above how we have access to all of these functions from the useForm hook. I've also set the mode to onTouched and the reValidateMode to onChange. This will dynamically validate our form as we cycle through the inputs.

  • mode : string
    • onChange | onBlur | onSubmit | onTouched | all = 'onSubmit'
  • reValidateMode : string
    • onChange | onBlur | onSubmit = onChange

Modes

  • onSubmit
    • Validation will trigger on the submit event and invalid input will attach onChange event listeners to re-validate them.
  • onBlur
    • Validation will trigger on the blur event.
  • onChange
    • Validation will trigger on the change event with each input, and lead to multiple re-renders. Warning: this often comes with a significant impact on performance.
  • onTouched
    • Validation will trigger on the first blur event. After that, it will trigger on event change event.
  • all
    • Validation will trigger on the blur and the change events.

Now let's go through a few key features.

Register

This is the main key concept of the React Hook Form, as you'll read in their documentation. It's required to register each input into the hook to allow access to its value, which will then be used for validation and submission.

Using the register functionality with an IonInput is just the same as using it with a standard HTML input.

<IonInput {...register("firstname")} />

Applying Validation

Obviously, one of the big advantages of using this is that we can easily apply validation without writing much code. Let's add validation options to our above input.

<IonInput {...register("firstname", { required: true, maxLength: 30 })} />

We've added a required flag set to true. This tells the hook that this input is required and should contain some value, and what follows, is the actual validation condition, in this case, a max length of 30.

We can also apply validation to an input without the use of the required flag. This can be useful if we still want to validate a field but not require it, take an age input for example;

<IonInput {...register("age", { min: 18, max: 99 })} />

The minimum number entered should be 18 and the max, 99.

Error Handling

In order to show errors to the user, we can make use of the errors we have access to as part ofr the formState from the hook.

Depending on when your validation happens, in this case, it'll happen onChange/onTouched, will depend when the errors object gets filled with potential erorrs that you can then use in whatever way you like;

...
<IonInput {...register("firstname", { required: true, maxLength: 30 })} />
{ errors.firstname &&  <IonBadge color="danger">First name is required</IonBadge> }
...

Obviously, we have no context or layout/styling around our input and error message here, but you can see how we can easily show an error message based on the automatic error handling and validation using React Hook Form.

Submitting our form

We need to get access to the values of the inputs, especially when the user submits the form, right? This is easy as well! We can hook into the handleSubmit function which accepts a callback function.

As part of your form onSubmit, you should call the handleSubmit and pass in a custom callback function to get access to the data held in your state hook.

...
const onSubmit = data => {

	console.log(data);
}

return (
	<form onSubmit={ handleSubmit(onSubmit) }>
...

The value we would see in our console at this point, if we take the two example inputs above, with all validation passed and no errors would be;

{firstname: "Alan", age: "27"}

At this point, all we would need to do to access our values and do something with them would be;

const onSubmit = data => {
	
	const firstname = data.firstname;
	const age = data.age;

	//	Submit code
	//	Here we could fire our form values off to global state or an API/backend
}

A more useful Example

Let's look at a real example and how we could use this effectively inside an Ionic React application.

Building an array of input objects to dynamically build a form

Let's build up an array called fields which will hold the firstname and age input along with al of their properties, required options and other general attributes.

const fields = [
	{
		label: "Firstname",
		required: true,
		requiredOptions: {
			maxLength: 10
		},
		props: {
			name: "firstname",
			type: "text",
			inputmode: "text",
			placeholder: "Enter a username"
		}
	},
	{
		label: "Age",
		required: true,
		requiredOptions: {
			min: 18,
			max: 99
		},
		props: {
			name: "age",
			type: "number",
			inputmode: "numeric",
			placeholder: "Enter your age"
		}
	}
];

Now in our return, all we need to do is map over our array, and pass the appropriate props and attributes to the right places using Ionic Components.

<form  onSubmit={ handleSubmit(onSubmit)  }>
	{ fields.map((field, index)  =>  {
		
		const  {  label, required, requiredOptions, props  }  =  field;
		
		return  (
			<IonItem  key={ `form_field_${ index }`  }  lines="full">
				<>
					<IonLabel  position="fixed">{  label  }</IonLabel>
					<IonInput  { ...props }  { ...register(props.name, {  required, ...requiredOptions })  }  />
				</>
				{  required  && errors[props.name]  && <IonIcon  icon={  alertCircleOutline  }  color="danger"  /> }
			</IonItem>

		);

	})}
	
	<IonButton  type="submit"  className="ion-margin-top" expand="full">Submit</IonButton>
</form>

This simple map will loop over our fields, destruct the array element and pass the props to the IonInput, along with the requiredOptions to the register function. We've also set up an error handling icon here as a way to show a different style of implementation instead of error text. However we could easily add an error message into the field object and dynamically display it as well / instead.

And.... That's pretty much it to get started with React Hook Form! There are lots of other features and functionality you can use as part of implementing forms and validation using this method, such as the trigger function etc and more unique functionality which you can check out via the documentation. However, this will help you get started using React Hook Form with your Ionic React apps!

Here is a link to the code of my implementation using React Hook Form

If this has helped you understand using the React Hook Form with Ionic React, or if you've implemented this into your own app then let me know!

Feel free to reach out on Twitter or share it below!

Discuss

Share this post

Level up your Ionic React skills. I'll send you handpicked tutorials, examples & resources

Plus, you'll be the first to know about premium content!

ionic logo

Read More...

Simple and effective way to create an add to cart animated button in Ionic React with Ionic Animations.

Animations

Using Ionic Animations to create an add to cart animated button in Ionic React

Simple and effective way to create an add to cart animated button in Ionic React with Ionic Animations.

11th June 2021

5 min read

I want to teach you how you can achieve routing programmatically in Ionic with React, with examples!

Routing

Routing, programmatically in Ionic React

I want to teach you how you can achieve routing programmatically in Ionic with React, with examples!

3rd June 2021

3 min read

I want to show you what tech and plugins I used to build this website and blog.

General

How I built this website and blog

I want to show you what tech and plugins I used to build this website and blog.

2nd June 2021

4 min read