Docs
React Hook Form

React Hook Form

Learn how to integrate Emblor with React Hook Form.

In this guide, we will take a look at integrating Emblor with React Hook Form, a popular form library for React applications. React Hook Form is a lightweight and performant library that allows you to build forms with ease. By integrating Emblor with React Hook Form, you can create a fully-featured tag input component that is highly customizable and accessible.

SportsProgrammingTravelMusicFood

These are the topics that you're interested in.

Installation

First, install Emblor and React Hook Form by running the following command:


npm install emblor react-hook-form
# Or, use any package manager of your choice.

Integration with React-Hook-Form

Integrating Emblor with react-hook-form allows for easy form validation, submission, and more complex forms management. Here's how to integrate effectively:

Basic integration


import { useForm, Controller } from 'react-hook-form';
import { Tag, TagInput } from 'emblor';
 
function TagForm() {
  const { control, handleSubmit, setValue } = useForm();
  const [tags, setTags] = React.useState<Tag[]>([]);
 
  const onSubmit = (data) => {
    console.log(data.tags); // Process tag data
  };
 
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        name="tags"
        control={control}
        render={({ field }) => (
          <TagInput
            {...field}
            placeholder="Enter a topic"
            tags={tags}
            className="sm:min-w-[450px]"
            setTags={(newTags) => {
              setTags(newTags);
              setValue('topics', newTags as [Tag, ...Tag[]]);
            }}
          />
        )}
      />
      <button type="submit">Submit</button>
    </form>
  );
}
 
export default TagForm;

Overall the integration is straightforward. We use the Controller component from react-hook-form to manage the input field. The Controller component takes a name prop, which is the name of the field in the form data. The render prop is a function that returns the input component. In this case, we return the TagInput component from Emblor.