skip to Main Content

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


  1. Chosen as BEST ANSWER

    Solution with alt images:

    edit.js

            <InspectorControls>
            <PanelBody icon={image} title="Alt do HeroImage" initialOpen={false}>
                <TextControl
                    label="hero image alt:"
                    value={attributes.imgAlt}
                    onChange={ ( val ) => setAttributes( { imgAlt: val } ) }
                />
            </PanelBody>
            </InspectorControls>
    
         <MediaUploadCheck>
            <MediaUpload
                onSelect={selectImage}
                allowedTypes={ ALLOWED_MEDIA_TYPES }
                value={ 1 }
                render={ ({open}) => {
                    return <img 
                        src={attributes.imgUrl}
                        onClick={open}
                        />;
                }}
            />
         </MediaUploadCheck>
    

    save.js

    export default function save( { attributes } ) {
    const blockProps = useBlockProps.save();
    return (
      <img className='classhere' src={attributes.imgUrl} alt={attributes.imgAlt}/>
    );
    }
    

    block.json

    "attributes": {
        "imgUrl": {
          "type": "string",
        },
        "imgAlt": {
          "type": "string"
        }
    }
    

  2. You will find it in the attributes variable. log the attributes variable in the console and you’ll see what other values you have in it.

    Login or Signup to reply.
  3. I usually do it like this to get the title for example:

    edit: ({attributes, setAttributes}) => {
            const {
                title,
                media
            } = attributes;
    
            return (<>{title}</>)
    }
    

    setAttributes is used to "set" them with new values.

    So for example:

    setAttributes({title: 'my new title'})
    

    See: https://developer.wordpress.org/block-editor/reference-guides/block-api/block-attributes/

    Login or Signup to reply.
  4. @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

    export default function Edit({ attributes, setAttributes }) {
        const hasImages = attributes.images.id !== undefined;
        console.log(attributes.images);
        return (
            <div {...useBlockProps()}>
                {hasImages && (
                    <MediaUpload
                        allowedTypes={['image']}
                        multiple={false}
                        value={attributes.images ? attributes.images.id : ''}
                        onSelect={(newImages) => setAttributes({ images: newImages })}
                        render={({ open }) => (
                            <div className="image">
                                <figure>
                                    <img src={attributes.images.url} alt={attributes.images.alt} />
                                </figure>
                                <div>
                                    <Button onClick={() => setAttributes({ images: '' })} className="button">Remove</Button>
                                </div>
                            </div>
                        )}
                    />
                )}
                {!hasImages && (
                    <MediaPlaceholder
                        icon={<BlockIcon icon="format-gallery" />}
                        labels={{
                            title: "Placeholder Title",
                            instructions: "Add a most excellent image.",
                        }}
                        onSelect={(newImages) => setAttributes({ images: newImages })}
                    />
                )}
            </div>
        );
    }
    

    Inside of block.json, my images attribute is type "object":

    "attributes": {
        "images": {
            "type": "object"
        }
    }
    

    I hope this helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search