#[BlockRenderer] How create a compontent to WP + GraphQL
3 messages · Page 1 of 1 (latest)
To create a basic BlockRenderer component for WordPress with GraphQL in Astro, you can follow these steps:
-
First, make sure you have set up WordPress as a headless CMS and enabled GraphQL in your WordPress installation.
-
Create a new Astro component file, e.g.,
BlockRenderer.astro, in yoursrc/components/directory. -
Here's a basic example of how your
BlockRenderer.astrocomponent might look:
---
const { blocks } = Astro.props;
const renderBlock = (block) => {
switch (block.name) {
case 'core/paragraph':
return `<p>${block.attributes.content}</p>`;
case 'core/heading':
return `<h${block.attributes.level}>${block.attributes.content}</h${block.attributes.level}>`;
// Add more cases for other block types as needed
default:
return '';
}
};
---
{blocks.map((block) => <Fragment set:html={renderBlock(block)} />)}
- To use this component, you'll need to fetch the post content from WordPress using GraphQL. In your page component (e.g.,
src/pages/[...slug].astro), you can do something like this:
---
import { useStoryblokApi } from '@storyblok/astro'
import BlockRenderer from '../components/BlockRenderer.astro';
const { slug } = Astro.params;
const query = `
query GetPost($slug: String!) {
post(id: $slug, idType: SLUG) {
content
}
}
`;
const variables = { slug };
const response = await fetch('YOUR_WORDPRESS_GRAPHQL_ENDPOINT', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ query, variables }),
});
const { data } = await response.json();
const blocks = JSON.parse(data.post.content);
---
<BlockRenderer blocks={blocks} />
This is a basic implementation and may need to be adjusted based on your specific WordPress setup and GraphQL schema. The key is to parse the content returned from WordPress into blocks and then render those blocks using the BlockRenderer component.
Remember to replace 'YOUR_WORDPRESS_GRAPHQL_ENDPOINT' with your actual WordPress GraphQL endpoint.