LoginSignup
1
0

More than 1 year has passed since last update.

React+MUI+React Hook Formでタグ入力フォームの作り方

Last updated at Posted at 2022-07-28

概要

大変だったのでシェア。

やりたかったかことは、タグ入力で使うフォーム。
オートコンプリート+テキスト入力+チップで構成してある。

React Hook Form的には外部ライブラリを使う場合はregisterではなく、controllerを使いましょう。ということだったのだが、デフォルト値のセットがどうやってやるのかよくわからなかったし、なぜかサブミットに値が入らなかった。
コード的には以下でできたよ。

もっといいのあったら教えてー

コード

uniq.jsx
  const [hogehoge, setHogehoge] = useState([]);

  const { control, handleSubmit, setValue, reset } = useForm({
    mode: "onChange",
    defaultValues,
  });

 const defaultValues = useMemo(() => {
    let defaultValue = {
      hogehoge: [],
    };

    if (hogehoge && hogehoge.length) {
      defaultValue.hogehoge = hogehoge;
      setHogehoge(defaultValue.hogehoge);
    }

    return defaultValue;
  }, [hogehoge]);

  useEffect(() => {
    reset(defaultValues);
  }, [defaultValues]);

  return (
      <Controller
        name={props.id}
        control={props.control}
        render={({ field, fieldState }) => (
          <FormControl fullWidth error={fieldState.invalid}>
            <InputLabel id={props.id + "-label"}>{props.label}</InputLabel>
            <Select
              {...field}
              labelId={props.id + "-label"}
              id={props.id}
              multiple
              value={props.value}
              onChange={props.handleOnChange}
              input={<OutlinedInput label={props.id} />}
              renderValue={(selected) => (
                <Box sx={{ display: "flex", flexWrap: "wrap", gap: 0.5 }}>
                  {selected.map((value) => (
                    <Chip key={value} label={value} />
                  ))}
                </Box>
              )}
            >
              {props.selective.map((selective) => (
                <MenuItem key={selective} value={selective}>
                  {selective}
                </MenuItem>
              ))}
            </Select>
            <FormHelperText>{fieldState.error?.message}</FormHelperText>
          </FormControl>
        )}
    )
 
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0