Creating a Re-usable react-hook-form Component Using Function as Child Components

Let’s say you created a login form using react-hook-form.

It will look something like this.

I extracted validation logic into a different file for ease of use.

But now you need to implement another login component in some other part of the website. How do you go about this?

The first way that comes to mind is using the same component and maybe passing in some props and using css to customize the different components as needed. This might work if the second login component is the same or slightly different from the first one, but if you need to have a completely different layout, things are going to get complicated quickly. Especially if you need to reuse the login functionality in more than 2 places.

Thankfully react gives us a good way to handle this using functions as child components . Here is a great video to watch if you don’t know about functions as child components

Here is what that would look like:

We are just passing the necessary variables and functions as parameters by calling props.children .

Now all we need to do is refactor Login component to use the LoginProvider .

We provide a function as a child of LoginProvider and that enables us to take parameters from LoginProvider and use them inside our Login components. By doing this we extract the Login functionality and can use it whenever we want.

This enables us to use the login and validation functionality without having to keep the form elements in a strict order.

Software Engineer