Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a image selected from input type = file in reactJS

I'm trying to display a image selected from my computer in my web app. I referred the following question which addresses the question i'm trying to fix.

How to display selected image without sending data to server?

I have my html part like this

 <div className="add_grp_image_div margin_bottom">       <img src={img_upload} className="add_grp_image"/>       <input type="file" className="filetype" id="group_image"/>       <span className="small_font to_middle">Add group image</span>       <img id="target"/>  </div> 

I want to display the selected image in

<img id="target"/> 

How can i do this?

I referred FileReader docs as well.

https://developer.mozilla.org/en-US/docs/Web/API/FileReader

like image 659
CraZyDroiD Avatar asked May 16 '17 04:05

CraZyDroiD


People also ask

How do I preview a selected image in React?

The React app we are going to build has a file input. When you select an image with this file input, an image preview will show up below it. There is also a “Remove This Image” button that lets you remove the selected image and the preview as well.

How do I display an image in React?

To display an image from a local path in React:Download the image and move it into your src directory. Import the image into your file, e.g. import MyImage from './thumbnail. webp' . Set the src prop of the image element to the imported image, e.g. <img src={MyImage} alt="horse" /> .


1 Answers

Try this

<input type="file" onChange={this.onImageChange} className="filetype" id="group_image"/> 

Add method to class

onImageChange = (event) => {   if (event.target.files && event.target.files[0]) {     let reader = new FileReader();     reader.onload = (e) => {       this.setState({image: e.target.result});     };     reader.readAsDataURL(event.target.files[0]);   } } 

or you can use URL.createObjectURL

onImageChange = (event) => {  if (event.target.files && event.target.files[0]) {    this.setState({      image: URL.createObjectURL(event.target.files[0])    });  } } 

And display image

<img id="target" src={this.state.image}/> 

For the hook version:

const [image, setImage] = useState(null)  const onImageChange = (event) => {  if (event.target.files && event.target.files[0]) {    setImage(URL.createObjectURL(event.target.files[0]));  } }  return (   <div>     <input type="file" onChange={onImageChange} className="filetype" />     <img src={image} alt="preview image" />   </div> ) 
like image 60
Giang Le Avatar answered Sep 22 '22 06:09

Giang Le