7
3

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 3 years have passed since last update.

【Typescript + React】e.target.files[0]のObject is possibly 'null'.エラー

Last updated at Posted at 2021-01-17

修正前

「Object is possibly 'null'.」のTypescriptエラーが発生

const SampleFunc: FC = () => {
  const onUploadImage = React.useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const file = e.target.files[0]; // エラー発生箇所
      // fileの処理
    },
    [],
  );

  return (
    <>
      <input type="file" onChange={onUploadImage} />
    </>
  );
};

export default SampleFunc;

修正内容

変更  e.target -> e.currentTarget
追記  if (e.currentTarget.files !== null) {/* 処理 */}

修正後

const SampleFunc: FC = () => {
  const onUploadImage = React.useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      if (e.currentTarget.files !== null) {
        const file = e.currentTarget.files[0];
        // fileの処理
      }
    },
    [],
  );

  return (
    <>
      <input type="file" onChange={onUploadImage} />
    </>
  );
};

export default SampleFunc;

追記

e.targetとe.currentTargetは違う場所を指しているらしい
https://qiita.com/sitilma/items/f26f5d16e455a0c68071

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?