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
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.