5
1

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.

Reactで input file サムネイル表示

Last updated at Posted at 2021-03-10

#Reactで input file サムネイル表示

<input type="file" /> で画像のサムネイルを表示したい

コンポーネントの内容

InputFile.tsx

import React, { useState } from 'react'

export interface Props {
  name: string
  defaultValue?: any
}

const InputFile: React.FC<Props> = ({ name, defaultValue }) => {
  const [value, setValue] = useState(defaultValue)
  const onChangeInputFile = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      const file = e.target.files[0]
      const reader = new FileReader()
      reader.onload = (e: any) => {
        console.log(e.target.result)
        setValue(e.target.result)
      }
      reader.readAsDataURL(file)
    }
  }
  return (
    <div>
      <input type="file" name={name} id="" src={value} onChange={onChangeInputFile} />
      <div>
        <img src={value} />
      </div>
    </div>
  )
}

export default InputFile

codepen

See the Pen React + TypeScript Starter by Hideto (@HidetoNagamatsu) on CodePen.

5
1
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
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?