reactjsfilereaderinput-type-file

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


Solution

  • 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 alt="preview image" src={image} />
      </div>
    )
    

    Class version

    render() {
       return (
         <div>
           <input type="file" onChange={this.onImageChange} className="filetype" />
           <img alt="preview image" src={this.state.image}/>
         <div/>
       )
    }
    
    onImageChange = (event) => {
     if (event.target.files && event.target.files[0]) {
       this.setState({image: URL.createObjectURL(event.target.files[0])});
     }
    }
    

    Another solution is to use FileReader

    onImageChange = (event) => {
      if (event.target.files && event.target.files[0]) {
        const reader = new FileReader();
        reader.onload = (e) => {
          setImage(e.target.result);
        };
        reader.readAsDataURL(event.target.files[0]);
      }
    }
    

    Working demo: https://codesandbox.io/s/priceless-cerf-my900b