42
44

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React / Next】同じ画像を選択してもonChangeが走るようにしたい

Posted at

個人的な備忘録です。

やりたいこと

  • input type="file" で画像を選択した時に、特定のメソッドを走らせたい
  • 画像選択時に、同じ画像を選択すると onChange が走らない
  • 同じ画像を選択しても、特定のメソッドを走らせたい

環境

  • React: 17.0.2
  • Next: 11.1.3

onClickパターン

// 省略

const handleChangeFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
  if (e.target.files && e.target.files.length > 0) {
    const file = e.target.files[0];
    setSelectedImageType(file.type);
    const resizedImage = await resizeFile(file, file.type);
    setSelectedImage(resizedImage);
    onOpen();
  }
};

<label>
	<Input
	  type="file"
	  accept={'image/jpeg, image/png, image/gif'}
	  onChange={(e) => handleChangeFile(e)}
	  onClick={(e) => {
	    (e.target as HTMLInputElement).value = '';
	  }}
	/>
</label>

refパターン

import { useRef, RefObject } from 'react';

export const Component = () => {
	inputRef: RefObject<HTMLInputElement>;
}

const handleChangeFile = (e: React.ChangeEvent<HTMLInputElement>) => {
  if (e.target.files && e.target.files.length > 0) {
    const reader = new FileReader();
    reader.onload = (e) => {
      if (!e.target || !e.target.result) {
        setSelectedImage('');
        return;
      }
      setSelectedImage(e.target.result.toString());
    };
    reader.readAsDataURL(e.target.files[0]);
	inputRef.current.value = '';
    onOpen();
  }
};

return (
  <label>
    <Input
	  ref={inputRef}
	  type="file"
	  accept={'image/jpeg, image/png, image/gif'}
	  onChange={(e) => handleChangeFile(e)}
	/>
  </label>
)
42
44
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
42
44

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?