07 June 2024
Material UI is one of the well-known open-source libraries for building UI with React. It offers a wide range of pre-built UI components that you can easily integrate into your projects. While it provides a great list of pre-built UI components, it still allows customization to tailor your specific UI requirements.
In this short blog post, I'll be sharing a component built using Material-UI's Textfield and Chip components. We'll also leverage React Hook Form for validation.
Let's start by installing the Material UI first.
Now let's create our component using the Material UI TextField and Chip.
InputChips.js
That's it. Our component is done. The TextField here acts as input only and does not hold the value. The Chip list is the output.
Now, let's integrate the React Hook Form. Install the package first.
Let's use our component and import what we need from react-hook-form
package at the App level for this demo.
App.js
And with this, our component is working as a controlled input. The maximumReached is a custom validation to showcase how well our component integrated with the React Hook Form. We are also utilizing the TextField properties to display the error from useForm()
.
Note: While React Hook Form excels at handling uncontrolled inputs, the controlled way will suffice for our example as performance isn't a concern in this example. To learn more about working with uncontrolled inputs, check out the register
method from useForm()
.
Check the CodeSandbox for the uncontrolled version.
To make it more awesome, let's add a feature where users can change the order of the chips. We will be using the react-easy-sort
package.
As the name suggests, React Easy Sort is really easy to use.
InputChips.js
We use SortableList to wrap the entire list, and SortableItem for each chip. SortableKnob helps us specify the DragIndicatorIcon as the element that initiates dragging. The icon is imported from @mui/icons-material
so don't forget to install it too.
Check the CodeSandbox for the full code and demo.
Learn more