0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

NextUIのInputはfileが添付できないから作った

Posted at

はじめに

みなさん、こんにちは torihaziです。

現在、RailsとNext.js(NextUI)でXクローンを作っているのですが

タイトルのことで少し詰まったので記事にしてみました

今作ってるもの
スクリーンショット 2024-10-18 13.57.54.png

結論

Buttonコンポーネントとinputタグで作ります。

export const InputFileButton = ({
  name,
  icon,
}: {
  name: string;
  icon: ReactNode;
}) => {
  const inputRef = useRef<HTMLInputElement>(null);

  const handleChange = (e) => {
    const file = e.target.files[0];
    console.log(file);
  };

  return (
    <>
      <IconButton onClick={() => inputRef.current?.click()}>{icon}</IconButton>
      <input
        ref={inputRef}
        accept="image/png image/jpeg"
        className="hidden"
        name={name}
        type="file"
        onChange={handleChange}
      />
    </>
  );
};

export const IconButton = ({
  children,
  onClick,
}: {
  children: ReactNode;
  onClick?: () => void;
}) => {
  return (
    <Button
      isIconOnly
      className="text-[#1C9BEF]"
      radius="full"
      variant="light"
      onClick={onClick}
    >
      {children}
    </Button>
  );
};

refを使ってbuttonクリックでinputと結びつけるみたいです。

form使っている際ににform外部のbuttonと連携しようとしてidとformを設定すればいけるので

似たようなの無いのかなと思って色々調べていたのですが、refで解決のようでした。

終わりに

こうすればいけます。
できたやつでこのinputのものは下のやつの画像アイコンのとこですね。

スクリーンショット 2024-10-18 14.06.14.png

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?