Skip to content

Instantly share code, notes, and snippets.

@bacoords
Last active December 18, 2023 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bacoords/483f8d856a5d176f22d8af8d36613c49 to your computer and use it in GitHub Desktop.
Save bacoords/483f8d856a5d176f22d8af8d36613c49 to your computer and use it in GitHub Desktop.
import { useSelect } from '@wordpress/data';
/**
* AttachmentImage
*
* This component is used to display an image from the media library.
* It's meant as a JS companion to the PHP function `wp_get_attachment_image()`.
*
* @link https://www.briancoords.com/getting-wordpress-media-library-images-in-javascript/
*
* @param {object} props
* @param {number} props.imageId The ID of the image to display.
* @param {string} props.size The size of the image to display. Defaults to 'full'.
* @returns {*} React JSX
*/
export default function AttachmentImage({ imageId, size = 'full' }) {
const { image } = useSelect((select) => ({
image: select('core').getMedia(imageId),
}));
const imageAttributes = () =>{
let attributes = {
src: image.source_url,
alt: image.alt_text,
className: `attachment-${size} size-${size}`,
width: image.media_details.width,
height: image.media_details.height,
};
if (image.media_details && image.media_details.sizes && image.media_details.sizes[size]) {
attributes.src = image.media_details.sizes[size].source_url;
attributes.width = image.media_details.sizes[size].width;
attributes.height = image.media_details.sizes[size].height;
}
return attributes;
};
return (
<>
{image && (
<img {...imageAttributes()} />
)}
</>
)
}
@bacoords
Copy link
Author

If you're using this outside of the block editor, you may need to import the WordPress core data store:

import { store as coreDataStore } from "@wordpress/core-data";

and use it in the useSelect:

const { image } = useSelect((select) => ({
	image: select(coreDataStore).getMedia(imageId),
}));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment