Gutenberg Tutorials: #3 Attributes — Demonstrated and Explained

What are Block Attributes?

How do Block Attributes work?

...
attributes: {
img: {
type: 'string'
},
title: {
type: 'string'
},
description: {
type: 'string',
default: 'Sample Text'
}
},
...
edit: props => {
const blockProps = useBlockProps( {
className: 'gtg-attrs-demo'
} );
const {
attributes,
setAttributes
} = props;
const {
img,
title,
description
} = attributes;

return (
<Fragment>
<InspectorControls>
<PanelBody title="Block Settings">
<TextControl
label="Image Source Url"
value={img ? img : ''}
onChange={(newVal) => setAttributes({ img: newVal })}
/>
<TextControl
label="Title Text"
value={title ? title : ''}
onChange={(newVal) => setAttributes({ title: newVal })}
/>
<TextControl
label="Description Text"
value={description ? description : ''}
onChange={(newVal) => setAttributes({ description: newVal })}
/>
</PanelBody>
</InspectorControls>
<div {...blockProps}>
<div className="img-column">
<img className="side-img" src={img} />
</div>
<div className="text-column">
<h1 className="title">{title}</h1>
<p className="description">{description}</p>
</div>
</div>
</Fragment>
);
},
<!-- wp:myfirstblock/gtg-attrs-demo {"img":"https://images.pexels.com/photos/325185/pexels-photo-325185.jpeg?auto=compress\u0026cs=tinysrgb\u0026dpr=3\u0026h=750\u0026w=1260","title":"City Above Clouds","description":"Lorem ipsum dummy text..."} -->
<div class="wp-block-myfirstblock-gtg-attrs-demo gtg-attrs-demo">
<div class="img-column"><img class="side-img" src="https://images.pexels.com/photos/325185/pexels-photo-325185.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=3&amp;h=750&amp;w=1260"/></div>
<div class="text-column">
<h1 class="title">City Above Clouds</h1>
<p class="description">Lorem ipsum dummy text...</p>
</div>
</div>
<!-- /wp:myfirstblock/gtg-attrs-demo -->

What are ‘Source’ and ‘Selector’?

{
url: {
type: 'string',
source: 'attribute',
selector: 'img',
attribute: 'src',
}
}
// { "url": "https://lorempixel.com/1200/800/" }

Founder of Arkon Digital. I’m not a code fanatic, but I’m always amazed by what code can do. The endless possibilities in coding is what fascinates me everyday.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store