Getting Started with Gutenberg Blocks Provider and Viewer
Quick Startâ
Make sure you have completed the initial setup for Faust at Getting Started.
Install the blocks package:
npm i @faustwp/blocks
Create a new folder inside your application root that you will place all the blocks. For conventional reasons, we name it wp-blocks
.
export default {};
``
Open `_app.js` and import the blocks provider, passing the list of blocks in the `config` property:
```jsx
import { WordPressBlocksProvider } from '@faustwp/blocks';
import blocks from '../wp-blocks';
<FaustProvider pageProps={pageProps}>
<WordPressBlocksProvider
config={{
blocks,
}}>
<Component {...pageProps} key={router.asPath} />
</WordPressBlocksProvider>
</FaustProvider>
Then, inside your templates you need to pass on the contentBlocks
data in your WordPressBlocksViewer
. The helper function flatListToHierarchical
is referenced here:
import { WordPressBlocksViewer } from '@faustwp/blocks';
import components from '../wp-blocks';
const { contentBlocks } = props.data.post;
const blocks = flatListToHierarchical(contentBlocks);
Example contentBlock
GraphQL query fragment. Setting flat: true
brings all the nodes back in one array instead of a bunch of separate nodes with their own arrays:
${components.CoreParagraph.fragments.entry}
contentBlocks(flat: true) {
__typename
renderedHtml
id: nodeId
parentId
...${components.CoreParagraph.fragments.key}
}
A Simple Block Exampleâ
This is a simple block called CoreParagraph
. The block is a p
tag that sets its content to attributes.content
which is passed in from the props.
CoreParagraph.fragments
does a WPGraphQL query for the content
and cssClassName
and sets it as the fragment CoreParagraphFragment
.
import { gql } from '@apollo/client';
import React from 'react';
export default function CoreParagraph(props) {
const attributes = props.attributes;
return (
<p
className={attributes?.cssClassName}
dangerouslySetInnerHTML={{ __html: attributes.content }}></p>
);
}
CoreParagraph.fragments = {
entry: gql`
fragment CoreParagraphFragment on CoreParagraph {
attributes {
content
cssClassName
}
}
`,
key: `CoreParagraphFragment`,
};
import
and export default
the CoreParagraph
Block in wp-blocks/index.js
:
import CoreParagraph from './CoreParagraph';
export default {
CoreParagraph,
};
Further Learningâ
More details on the WordPressBlocksProvider.
More details on the WordPressBlocksViewer.
Continue learning about the project structure, how to change styles, layout, etc. by referencing the Example Project Walkthrough Structure.