Search code examples
reactjsinput-type-file

Displaying an image of a file from input


I am trying to show an image of a file that was selected from input without sending data to the server.

Wanted to do it with URL.createObjectUrl.

const onImageChange = (event) => {
        if (event.target.files && event.target.files[0]) {
          this.setState({
            image: URL.createObjectURL(event.target.files[0])
          });
        }
       } 
<input type="file" 
      onChange={onImageChange} 
      className="filetype" 
      id="group_image"/>

And then pass an image inside

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

But i get undefined has no properties with this code. So does anyone know how to do it?

EDIT: https://codesandbox.io/s/restless-sun-61uui?file=/src/App.js

Full code:

import React from 'react'

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

    return (
        <div>
      <input type="file" 
      onChange={onImageChange} 
      className="filetype" 
      id="group_image"/>
      
      <img 
      id="target" 
      src={this.state.image}/> 
        </div>
    )
}

export default Addfile

Solution

  • You are using a functional component. There is not this.state, isn't it?

    You should use useState. I updated the codesandbox for you: https://codesandbox.io/s/zealous-noether-3tz4f?file=/src/App.js