Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Uploading a picture in React

My React component has the next code:

              <Row>
            <Col>
                <p>Select Image</p>
                <input type="file" name="myImage" onChange={this.handle_userImage_change} />                
            </Col>
            <Col>
                <img src={this.state.userImage} />
            </Col>

          </Row>

and also the next callback:

 handle_userImage_change = (event) => {
  console.log('handle_userImage_change>event=78658');
  console.log(event)
}

From the event parameter I want to get the file data to convert it to base64 using readAsDataUrl so later I can assign this value to

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this.state.userImage

and in this way show the respective picture at the <img … > section.

a) What is the field from the event object I need to use?

b) Is the syntax correct for the <img ..> section?

>Solution :

You can access the image data from files property in event.target object like this event.target.files[0]. files is an array and the image is stored as first element.

You need to use URL.createObjectURL() to create an url representation of the image.
You can store this in a state variable and then use it to pass to src prop of the image.

const [image, setImage] = useState("");

const handleFileUpload = (e) => {
  setImage(URL.createObjectURL(e.target.files[0]));
};

return <img src = {image} alt = "" / >

Note that on chrome, if you re-upload the same image again when it is already selected, onChange event won’t trigger. Follow this to solve the issue.

HTML input file selection event not firing upon selecting the same file.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading