Upload Image in React js function component

Prafull Kumar
Aug 4, 2021

Here e.target.files will return an array “ FileList [ File ] “

So we need to do as const data= e.target.files[0] this will return and object

{  name: "carbon(1).png",lastModified: 1627472392919, webkitRelativePath: “”,size: 143187,type: “image/png” }

For display image we need use URL.createObjectURL(file)

<img src={URL.createObjectURL(file)}/>

See below code

import React, { useState } from 'react'const uploadForm = (props) => {
const [file,setFile]=useState('')

const handleChange=(e)=>{
const data=e.target.files[0]
setFile(data)
}
return (
<div>
<input type="file" onChange={handleChange}/>
{file &&

<div>
<span>{file.name}</span>
<img src={URL.createObjectURL(file)}/>
</div>
}
</div>
)
}
export default uploadForm

--

--