Custom Blocks
The Organic Core Frontend package comes with various pre-defined CMS blocks that are typically utilized for page composition or content creation. However, there may arise situations where additional blocks are required to be added to the backend CMS. In such scenarios, it is essential to provide a mechanism for the frontend to interpret the rendering of the custom blocks. To achieve this, the Theme API incorporates a feature that facilitates the extension of support for custom blocks called extend
. This enables developers to effortlessly customize and integrate new blocks into the Organic Core Frontend package.
Example
In your theme file you can extend blocks as follows:
import { gql } from 'graphql-request';
const SomeCustomBlockComponent = dynamic(
() => import('path/to/SomeCustomBlockComponent'),
);
const someCustomBlockFragment = gql`
fragment SomeCustomBlockFragment on SomeCustomBlock {
// ... fields here
}
`
const theme = createTheme(
//...
extend: {
blocks : [
{
// CMS Registered block name
name: 'SomeCustomBlock',
// React Component
component: SomeCustomBlockComponent,
// Fragment as a gpl string
fragment: someCustomBlockFragment.
}
]
};
);
export default theme;
In the provided code example, the extend
attribute is utilized to extend the functionality of the theme by defining new blocks or modifying existing ones. It is an object that contains two sub-attributes: blocks and fragments.
blocks
: The blocks
attribute is an array of objects that contain the following three properties:
name
: The name used to register the block in the CMS.fragment
: The GraphQL fragment that represents the block's data structure and fields.component
: The React component that defines the custom rendering of the block.
Creating a block component
To create a new block component you will need to use RenderBlockProps
prop type. If you're extending the block with an additional fragment, it may be necessary to redefine the block prop.
Below is a sample component for the 'acf/compact-post-list' block:
import { ComponentType } from 'react';
import { RenderBlockProps } from '@orgnc/core/components/blocks/Blocks/helpers/RenderBlock';
import type { BlockFragment } from '@orgnc/core/lib/wordpress/api/fragments/blocksFragment';
import { IAcfCompactPostListBlockFragment } from '@orgnc/core/generated/graphql-operations';
const AcfCompactPostListBlockComponent: ComponentType<RenderBlockProps> = ({
area,
block,
frequency,
}) => {
const acfCompactPostListBlock =
block as unknown as BlockFragment<IAcfCompactPostListBlockFragment>;
// Here you can get all the attributes added to the fragment
const { attributes } = acfCompactPostListBlock;
return (
<div data-og-block-area={area} data-og-block-nth={frequency}>
<pre>{JSON.stringify(attributes, null, 2)}</pre>
</div>
);
};
export default AcfCompactPostListBlockComponent;