WordPress.org

WordPress Developer Blog

Understanding block attributes

There’s more to attributes than might initially meet the eye. A block can have as many attributes as you like, and these are defined in the attributes property of the block’s block.json file. 

Block attributes are essentially variables that store data or content for the block. Users can modify and update the values stored there. But where does the data or content come from?

An attribute can get its value from a defined default, or from user input. It can also be populated with a value retrieved from the stored content. The values retrieved in this last way can, in fact, come from a variety of different places in the stored content and can be retrieved in various ways. Let’s dig in.

The Anatomy of a simple block

Consider this simple block. It has a single attribute, namely content:

"attributes": {
  "content": {
    "type": "string"
  }
}

The Edit() function implements a RichText component that displays and updates the content attribute:

import { useBlockProps, RichText } from '@wordpress/block-editor';

export default function Edit( { attributes, setAttributes } ) {
  return (
    <RichText
      { ...useBlockProps() }
      placeholder="Type something here..."
      tagName="div"
      value={ attributes.content }
      onChange={ ( val ) => setAttributes( { content: val } ) }
    />
  );
}

The save() function does what you expect it to do and merely saves the content:

import { useBlockProps, RichText } from '@wordpress/block-editor';

export default function save( { attributes } ) {
  return (
    <RichText.Content
      { ...useBlockProps.save() }
      tagName="div"
      value={ attributes.content }
    />
  );
}

You’ll see this in your editor: