So I'm creating form that let's user upload few images. I'm using react-dropzone to make it cooler ;p Unfortunately after choosing image my has undefined src attribute. Here's my code:
export const ImageInput = (props) => {
const imagePreviews = props.images.map(image => {
return <ImagePreview key={image.id} image={image.image}/>
})
return (
<div>
<Dropzone
className="dropzone"
multiple={true}
accept="image/*"
onDrop={props.addImage}> I STORE THE IMAGES IN PARENT COMPONENT
<p>drop or click here</p>
</Dropzone>
<ul>
{imagePreviews}
</ul>
</div>
)
}
And this is single ImagePreview component
export const ImagePreview = (props) => {
let imagePreviewUrl = "";
let reader = new FileReader();
reader.readAsDataURL(props.image)
reader.onloadend = () => {
imagePreviewUrl = reader.result;
}
console.log(imagePreviewUrl)
return (
<li className="">
<img className="image-preview" src={imagePreviewUrl} />
</li>
)
}
Using react tools for browser I can prove that images are being saved correctly image
Where am I making a mistake?
reader.onloadend is async so "ImagePreview" will return before imagePreviewUrl has value. You cant use this code for "ImagePreview"
class ImagePreview extends React.Component {
constructor() {
super();
this.state= {imagePreviewUrl: ''}
}
componentWillMount() {
let reader = new FileReader();
reader.readAsDataURL(props.image)
reader.onloadend = () => {
this.setState({imagePreviewUrl: reader.result})
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.