How to Fetch Alt Text of Image with Gutenberg

Posted on: September 20th, 2024
By: Tadeo Martinez

Here’s the constant function:

const updateColumn = (columnIndex, field, value) => {
		setAttributes({
			columns: columns.map((column, index) => {
				if (index === columnIndex) {
					// Check if the value is an object (in case of multiple updates)
					if (typeof value === 'object' && value !== null) {
						return {
							...column,
							...value, // Spread the object fields
						};
					}
					return {
						...column,
						[field]: value, // Single field update
					};
				}
				return column;
			}),
		});
	};

Here’s the component:

<MediaUploadCheck>
    <MediaUpload
        onSelect={(media) =>
            updateColumn(index, 'img', { img: media.url, alt: media.alt })
        }
        type="image"
        allowedTypes={['image']}
        value={column.img}
        render={({ open }) => (
            <div>
				<p className={`small`}>{__('Alt Texts:')} {column.alt}</p>
                {column.img && (
                    <Button
                        isLink
                        isDestructive
                        onClick={() => updateColumn(index, 'img', '')}
                    >
                        {__('Remove Col Image')}
                    </Button>
                )}
                <Button
                    onClick={open}
                    icon="upload"
                    className="editor-media-placeholder__button is-button is-default is-large"
                >
                    {__('Select Col Image')}
                </Button>
            </div>
        )}
    />
</MediaUploadCheck>

Have any questions or comments? Write them below!


Leave a Reply

Your email address will not be published. Required fields are marked *