Hi i don’t know how to get alt image by media upload in gutenberg custom block.
edit.js:
function selectImage(value) {
console.log(value);
setAttributes({
imgUrl: value.sizes.full.url,
})
}
<MediaUploadCheck>
<MediaUpload
onSelect={selectImage}
allowedTypes={ ALLOWED_MEDIA_TYPES }
value={ 1 }
render={ ({open}) => {
return <img
src={attributes.imgUrl}
onClick={open}
/>;
}}
/>
</MediaUploadCheck>
save.js:
<div className='flex columns-xl justify-center items-center content-center'>
<img className='max-w-sm' src={attributes.imgUrl} alt=""/>
</div>
Thanks for your help me 🙂
4
Answers
Solution with alt images:
edit.js
save.js
block.json
You will find it in the
attributes
variable. log theattributes
variable in the console and you’ll see what other values you have in it.I usually do it like this to get the
title
for example:setAttributes is used to "set" them with new values.
So for example:
See: https://developer.wordpress.org/block-editor/reference-guides/block-api/block-attributes/
@Vijay Hardaha is correct in that with newer versions of Gutenberg, MediaUpload returns an image as an object with a lot of information, including alt, id, and url. In my script, notice the console.log just before the return. Once an image is selected, it will will show you the object details.
In this example I am using the placeholder similar to this post and I am extracting the image src and alt based on this post.
Note: That second post also explains how to replace MediaPlaceholder with the selected image using the "hasImages" const. The original is a gallery so it returns an array of objects. I only wanted one image so I changed it.
Inside of edit.js
Inside of block.json, my images attribute is type "object":
I hope this helps!