Created
September 14, 2020 12:44
-
-
Save jacobarriola/45e091a87eb24d944fced3d05bd7d741 to your computer and use it in GitHub Desktop.
Recursive block component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Blocks = ({ blocks }) => { | |
return blocks.map(block => ( | |
<RecursiveBlockRenderer | |
key={`${block.name}_${block.order}`} | |
block={block} | |
/> | |
)) | |
} | |
function RecursiveBlockRenderer({ block }) { | |
switch (block.name) { | |
case 'core/paragraph': | |
return <ParagraphBlock {...block} /> | |
case 'core/html': | |
return <HtmlBlock {...block} /> | |
case 'core/columns': | |
return <ColumnsBlock {...block} /> | |
case 'core/column': | |
return <ColumnBlock {...block} /> | |
// add the rest of your blocks... | |
default: | |
return true | |
} | |
} | |
function ParagraphBlock({ attributes }) { | |
return ( | |
<p | |
{...(attributes.align ? { className: `text-${attributes.align}` } : {})} | |
dangerouslySetInnerHTML={{ __html: attributes.content }} | |
/> | |
) | |
} | |
function HtmlBlock({ attributes }) { | |
return <span dangerouslySetInnerHTML={{ __html: attributes.content }} /> | |
} | |
function ColumnsBlock({ attributes, innerBlocks }) { | |
const { className, columns } = attributes | |
return ( | |
<ul | |
className={`${ | |
className ? className : '' | |
} container grid gap-10 grid-cols-1 md:grid-cols-${columns}`} | |
> | |
{innerBlocks && | |
innerBlocks.map(inner => ( | |
<RecursiveBlockRenderer | |
key={`innerBlock_${inner.name}_${inner.order}`} | |
block={inner} | |
/> | |
))} | |
</ul> | |
) | |
} | |
function ColumnBlock({ innerBlocks }) { | |
return ( | |
<li> | |
{innerBlocks && | |
innerBlocks.map(inner => ( | |
<RecursiveBlockRenderer | |
key={`innerBlock_${inner.name}_${inner.order}`} | |
block={inner} | |
/> | |
))} | |
</li> | |
) | |
} | |
// In a page/component somewhere (contrived example) | |
function PageBlockEditorSample({ data }) { | |
const { blocksJSON } = data.wpPage | |
return ( | |
<Layout> | |
<Blocks blocks={JSON.parse(blocksJSON)} /> | |
</Layout> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment