Reputation: 541
My Objective is to show an image in avatar, If i could on the avatar icon and choose an image file then it should display the image in avatar. But i couldn't able to do that.
Can anyone help me in displaying the image in avatar?
Upvotes: 0
Views: 744
Reputation: 496
You should do like:
onImageChange = event => {
let file = URL.createObjectURL(event.target.files[0]);
console.log("File", file);
if (file === undefined) {
console.log("File removed");
} else {
this.setState({
image: file
});
}
};
and render
<Avatar src={this.state.image || '/static/images/avatar/1.jpg'} width="250" height="250" />
dont forget to revoke on unmount
componentWillUnmount() {
URL.revokeObjectURL(this.state.image);
}
Upvotes: 3
Reputation: 1285
Please use the image saved to the state. As below
<Avatar src={this.state.image} width="250" height="250" />
In the constructor, load it with the default value.
constructor(props) {
super(props);
this.state = {
'image': '/static/images/avatar/1.jpg'
};
}
And the image change event should be
onImageChange = event => {
let file = URL.createObjectURL(event.target.files[0]);
console.log("File", file);
if (file == undefined) {
console.log("File removed");
} else {
this.setState({
image: file
});
}
};
Upvotes: 0