I have a functional component with the following hook:-
const [imagePreview, setImagePreview] = useState('');
Later on, the change event, I have this:-
if (imagePreviewUrl) {
setImagePreview( (<div>
<br/> <img src={imagePreviewUrl} alt="icon" width="200" />
</div>));
}
Looks like it doesn't set anything. how do I set it? I could do it as:-
let imagePreview = null;
if (imagePreviewUrl) {
imagePreview = (<div>
<br/> <img src={imagePreviewUrl} alt="icon" width="200" />
</div>);
}
But it is bit ugly. I think useState is the recommended way to do it.
Update with more code:-
const fileChangedHandler = event => {
setSelectedFile(event.target.files[0]);
let reader = new FileReader();
reader.onloadend = () => {
setImagePreviewUrl(reader.result);
}
reader.readAsDataURL(event.target.files[0])
if (imagePreviewUrl) {
// can't break into multiline, sytax error
setImagePreview('(<div><br/> <img src={imagePreviewUrl} alt="icon" width="200" /> </div>)');
}
return (
<div>
<label>Profile picture: </label>
<input className="Column" type="file" accept="image/*"
onChange={(e) => {fileChangedHandler(e)}} />
// I want to show the selected image here as preview before upload
{ imagePreview }
</div>
)
Hopefully, I will give a clear understanding. What is my intention?