Building a Reusable Form Control Component with React Hook Form and Material-UI

Hardik Desai avatar
Hardik Desai

14 October 2024

2 min read
Building a Reusable Form Control Component with React Hook Form and Material-UI

Description

Dive into the world of form control components! Learn how to create a versatile and reusable FormControlBox component using React Hook Form and Material-UI. This blog post provides a step-by-step guide and code examples to simplify your form handling in React applications.

Summary

This Cheat for Shortcut of Form Control TextField in react-hook-form Library with MUI. Forms are an integral part of many web applications. However, handling forms and form validation can become complex. In this article, we'll introduce you to the FormControlBox component—a reusable solution that streamlines form control and validation using React Hook Form and Material-UI.

Installation Guide

  • Installing React Hook Form only takes a single command and you're ready to roll.
1
npm install react-hook-form
  • Installing MUI in React and Next JS
1
npm install @mui/material @emotion/react @emotion/styled

Source Code

1
import React from 'react'
2
import { TextField, FormControl, FormHelperText } from '@mui/material'
3
import { Control, Controller } from 'react-hook-form'
4
5
interface FormControlBoxProps {
6
label: string
7
name: string
8
control: Control<any> // Update the type if needed
9
errors: any
10
placeholder?: string
11
multiline?: boolean
12
rows?: number
13
isDisabled?: boolean
14
}
15
16
const FormControlBox: React.FC<FormControlBoxProps> = ({
17
label,
18
name,
19
control,
20
errors,
21
placeholder,
22
multiline,
23
rows,
24
isDisabled
25
}) => {
26
return (
27
<FormControl fullWidth>
28
<Controller
29
name={name}
30
control={control}
31
rules={{ required: true }} // Add more validation rules as needed
32
render={({ field: { value, onChange, onBlur } }) => (
33
<TextField
34
disabled={isDisabled}
35
label={label}
36
value={value}
37
onBlur={onBlur}
38
onChange={onChange}
39
error={Boolean(errors[name])}
40
placeholder={placeholder}
41
multiline={multiline}
42
rows={rows}
43
/>
44
)}
45
/>
46
{errors[name] && <FormHelperText sx={{ color: 'error.main' }}>{errors[name].message}</FormHelperText>}
47
</FormControl>
48
)
49
}
50
51
export default FormControlBox


Join the newsletter

Subscribe for weekly updates. No spams ever!

Copyright © 2024 | Hardik Desai | All Rights Reserved