Closed2

同じファイルを2回以上選択した時にinput[type='file']のonChangeが発火しない

tara is oktara is ok

原因

ブラウザの仕様で同一ファイルの場合はonChangeが発火しないらしい

解決方法

if (ref.current) ref.current.value = ''で初期化する必要がある

コード

export const CsvInput: FC<Props> = ({ children, onChange, ...props }) => {
  const ref = useRef<HTMLInputElement>(null)
  return (
    <Button onClick={() => ref.current?.click()} {...props}>
      {children}
      <Input
        hidden
        ref={ref}
        type="file"
        accept=".csv"
        onChange={({ target }) => {
          if (!target.files) {
            //todo:error
            return
          }
          onChange(target.files[0])
          //ここを追加 ✅
          //note: ブラウザの仕様で同じファイルを選択してもchangeイベントが発火しないため、valueをクリアする
          if (ref.current) ref.current.value = ''
        }}
      />
    </Button>
  )
}
このスクラップは3ヶ月前にクローズされました