DEV Community

Ahmet Karakuş
Ahmet Karakuş

Posted on

React Hook Form with MUI: TypeScript-Supported Generic Form Components

In my projects, I often prefer using the trio of MUI, RHF, and ZOD/YUP. Why, you ask? Because there’s something appealing about starting a new project every other day and never looking at it again.

Image description

So, when kicking off a new project, here are my steps:

  • I pick the colors that match my mood that day
  • set up my theme with MUI
  • and voilà… I start managing my form processes with RHF and ZOD. (Of course, after setting up the usual suspects like the router and other basics).

However, I’ve noticed that when using RHF — especially with the Controller— the code tends to get lengthy. For instance, let’s look at this Autocomplete code block:

Image description

Just to display a few cities in a fancy searchable dropdown, we ended up writing 29 lines of code. To avoid having to revisit code that slows down my flow, I created RHF-compatible form components with TypeScript-supported generic types. Now, let’s take a look at the above Autocomplete component again with this approach:

Image description

Image description

If, like me, reducing the number of lines of code makes you forget about life’s problems, future worries, and state issues, you can explore all these form components from this github repo. Here is the list of the components:

  • Autocomplete / MultiAutocomplete
  • Checkbox
  • DatePicker / DateTimePicker
  • Radio
  • Select
  • Slider
  • Switch
  • TextField
  • Form

Happy coding…

Top comments (0)