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.
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.
1npm install react-hook-form
1npm install @mui/material @emotion/react @emotion/styled
1import React from 'react'2import { TextField, FormControl, FormHelperText } from '@mui/material'3import { Control, Controller } from 'react-hook-form'45interface FormControlBoxProps {6label: string7name: string8control: Control<any> // Update the type if needed9errors: any10placeholder?: string11multiline?: boolean12rows?: number13isDisabled?: boolean14}1516const FormControlBox: React.FC<FormControlBoxProps> = ({17label,18name,19control,20errors,21placeholder,22multiline,23rows,24isDisabled25}) => {26return (27<FormControl fullWidth>28<Controller29name={name}30control={control}31rules={{ required: true }} // Add more validation rules as needed32render={({ field: { value, onChange, onBlur } }) => (33<TextField34disabled={isDisabled}35label={label}36value={value}37onBlur={onBlur}38onChange={onChange}39error={Boolean(errors[name])}40placeholder={placeholder}41multiline={multiline}42rows={rows}43/>44)}45/>46{errors[name] && <FormHelperText sx={{ color: 'error.main' }}>{errors[name].message}</FormHelperText>}47</FormControl>48)49}5051export default FormControlBox
Join the newsletter
Subscribe for weekly updates. No spams ever!
Copyright © 2024 | Hardik Desai | All Rights Reserved