#[BlockRenderer] How create a compontent to WP + GraphQL

3 messages · Page 1 of 1 (latest)

stiff krakenBOT
#

Hi @lyric loom. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To create a basic BlockRenderer component for WordPress with GraphQL in Astro, you can follow these steps:

  1. First, make sure you have set up WordPress as a headless CMS and enabled GraphQL in your WordPress installation.

  2. Create a new Astro component file, e.g., BlockRenderer.astro, in your src/components/ directory.

  3. Here's a basic example of how your BlockRenderer.astro component 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)} />)}
  1. 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.

For more detailed information on working with WordPress and Astro, you can refer to the Headless WordPress & Astro guide (https://docs.astro.build/en/guides/cms/wordpress/) in the Astro documentation.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: