Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete tag in uncontrolled "ChipInput" using react hook form

I'm using react-hook-form to handle form values, Its working fine for all other input types like TextFeild, Select from material but facing issues with "material-ui-chip-input" as adding tag working fine but not able to delete tag on click of cross button or hitting backspace. I'm struggling on this from a long. Anyone please help in it.

import React from "react";
import FormControl from "@material-ui/core/FormControl";
import { Controller } from "react-hook-form";

import ChipInput from "material-ui-chip-input";

const ReactHookFormChips = ({
  name,
  label,
  control,
  defaultValue,
  children,
  rules,
  error,
  chipsError,
  ...props
}) => {
  const labelId = `${name}-label`;
  return (
    <FormControl {...props}>
      <Controller
        as={
          <ChipInput
            label={label}
            helperText={chipsError}
            error={error}
          />
        }
        name={name}
        control={control}
        defaultValue={defaultValue}
        rules={rules}
      />
    </FormControl>
  );
};
export default ReactHookFormChips;


calling this component like

<ReactHookFormChips
  id="levelLabel"
  name="tags"
  label="Select Tags"
  control={control}
  defaultValue={[]}
  margin="normal"
  error={!!errors?.tags}
  rules={{ required: true }}
  chipsError={errors?.tags && "Tag is required."}
/>
like image 252
Rupinderpal Thind Avatar asked Oct 30 '25 22:10

Rupinderpal Thind


1 Answers

I fixed it using render prop.

import React from "react";
import FormControl from "@material-ui/core/FormControl";
import InputLabel from "@material-ui/core/InputLabel";
import { Controller } from "react-hook-form";

import ChipInput from "material-ui-chip-input";

const ReactHookFormChips = ({
  name,
  label,
  control,
  defaultValue,
  children,
  rules,
  error,
  chipsError,
  ...props
}) => {
  const labelId = `${name}-label`;
  return (
    <FormControl {...props}>
      <Controller
        render={({ onChange, onBlur, value }) =>
          <ChipInput
            onChange={onChange}
            label={label}
            helperText={chipsError}
            error={error}
          />
        }
        name={name}
        control={control}
        defaultValue={defaultValue}
        rules={rules}
      />
    </FormControl>
  );
};
export default ReactHookFormChips;
like image 179
Rupinderpal Thind Avatar answered Nov 01 '25 12:11

Rupinderpal Thind