after uploading a photo my block is selected, so I can change properties. But when I select another block, then by clicking on that photo I can’t select my block. I can select only through list view. Does anybody know how I can fix it?
blocks.registerBlockType( 'testblock/my-image', {
apiVersion: 2,
title: 'My image',
icon: 'format-image',
category: 'media',
example: {
attributes: {
id: '123',
alt: '',
url: 'http://mypage/wp-content/uploads/2021/02/hairdrayer.jpg'
},
},
attributes: {
id: {
type: 'number',
default: 0
},
alt: {
type: 'string',
default: ""
},
url: {
type: 'string',
default: ""
}
},
edit: ( props ) => {
return (
<>
{
<InspectorControls>
<PanelBody title="Image Settings" initialOpen={ true }>
{ props.attributes.id != 0 &&
<>
<PanelRow>
<TextControl
onChange={ newAlt => props.setAttributes({ alt: newAlt }) }
value={ props.attributes.alt }
help="Describe the purpose of the image. Leave empty if the image is purely decorative."
label="Alt Text"
/>
</PanelRow>
</>
}
</PanelBody>
</InspectorControls>
}
{ props.attributes.id === 0 &&
<MediaPlaceholder
onSelect={ (media) => {
props.setAttributes({
id: media.id,
alt: media.alt,
url: media.url
})
}}
allowedTypes = { [ 'image/gif', 'image/jpeg', 'image/png', 'image/svg+xml' ] }
multiple = { false }
labels = { {
title: 'Responsive image',
instructions: 'Upload an image file, pick one from your media library.'
} }
/>
}
<img
src={ props.attributes.url }
alt={ props.attributes.alt }
/>
</>
);
},
save: ( props ) => {
return (
<img
src={ props.attributes.url }
alt={ props.attributes.alt }
/>
);
},
});
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
When using apiVersion: 2 you must use the new useBlockProps hook to implement standard block behavior for your custom block. In your case you would “tell” the editor to treat your <img> as a block wrapper. This needs to be implemented in Edit and in Save and is explained here in detail: https://make.wordpress.org/core/2020/11/18/block-api-version-2/
Alternatively you could leave out apiVersion: 2 and try again. The editor will automatically add a wrapper element to your block enabling standard block behaviour.
Hope this helps.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0