DEV Community

Cover image for Material-UI Select with React Hook Form
Krishna Nigalye
Krishna Nigalye

Posted on

Material-UI Select with React Hook Form

My experience with React hook Form (RHF) is amazing so far. When you are using external css libraries with react hook form, you have to make few adjustments for example in place of ref, you have to use inputRef to pass the register method of RHF.

In this post, I would like to share a solution to the problem of adding validation to Select component of Material-UI* with RHF. Implementing select box is not hard. You can do that with TextField and also with Select component of Material-UI but adding validation can give you a headache.

This is solution I implemented for adding select box with validations.

<Controller
  as={
    <Select>
     {options.map((option, index) => (
      <MenuItem key={index} value={option}>
        {option}
      </MenuItem>
     ))}
    </Select>
    }
  name={options_name}
  control={control}
  defaultValue=""
  rules={{ required: true }
/>
Enter fullscreen mode Exit fullscreen mode

So validation worked for me by adding the following attribute to the controller.

rules={{ required: true }}
Enter fullscreen mode Exit fullscreen mode

I hope this will be helpful.

Top comments (1)

Collapse
 
0xldev profile image
0xLDev

Good brother