Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Documenting innerBlocks in save function #66689

Merged
merged 1 commit into from
Dec 23, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion docs/reference-guides/block-api/block-edit-save.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,9 +183,34 @@ save: ( { attributes } ) => {
```



When saving your block, you want to save the attributes in the same format specified by the attribute source definition. If no attribute source is specified, the attribute will be saved to the block's comment delimiter. See the [Block Attributes documentation](/docs/reference-guides/block-api/block-attributes.md) for more details.

### innerBlocks

There is a second property in the props passed to the `save` function, `innerBlocks`. This property is typically used for internal operations, and there are very few scenarios where you would need to use it.

`innerBlocks`, when initialized, is an array containing object representations of nested blocks. In those rare cases where you might use this property,
it can help you adjust how a block is rendered. For example, you could render a block differently based on the number of nested blocks or if a specific block type is present..


```jsx
save: ( { attributes, innerBlocks } ) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like it's a convenient alternative to another way to check inner blocks:

const blockProps = useBlockProps.save( { className } );
const innerBlocksProps = useInnerBlocksProps.save( blockProps );
return (
<figure { ...innerBlocksProps }>
{ innerBlocksProps.children }

I'm not entirely sure what the difference exactly is. However, I wanted to document it for completeness.

const { className, ...rest } = useBlockProps.save();

// innerBlocks could also be an object - react element during initialization
const numberOfInnerBlocks = innerBlocks?.length;
if ( numberOfInnerBlocks > 1 ) {
className = className + ( className ? ' ' : '' ) + 'more-than-one';
};
const blockProps = { ...rest, className };

return <div { ...blockProps }>{ attributes.content }</div>;
};
```


Here, an additional class is added to the block if number of inner blocks is greater than one, allowing for different styling of the block.

## Examples

Here are a couple examples of using attributes, edit, and save all together.
Expand Down
Loading