Skip to content

Instantly share code, notes, and snippets.

@henrikwirth
Last active December 7, 2020 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henrikwirth/e68322b960b6546291a8d4abe51d4f18 to your computer and use it in GitHub Desktop.
Save henrikwirth/e68322b960b6546291a8d4abe51d4f18 to your computer and use it in GitHub Desktop.
WPGraphQL ACF Flexible Layout mapping
import loadable from '@loadable/component';
const AcfComponents = {
Hero: loadable(() => import('../Hero/Hero')),
Grid: loadable(() => import('../Grid/Grid')),
};
export default AcfComponents;
import React from 'react';
import AcfComponents from './AcfComponents';
const FlexibleLayout = ({ layout }) => {
if (!layout?.__typename) {
return (
<section id={layout?.id} className="page missing">
<div className="inner">
Some ACF component is missing, which is not passed as layout. This means something in the schema is broken for
this component. Check build console errors.<span>🙅‍</span>
</div>
</section>
);
}
const indexOfLastUnderscore = layout?.__typename.lastIndexOf('_');
const type = layout.__typename.substring(indexOfLastUnderscore + 1);
const ComponentName = AcfComponents[type];
if (!ComponentName) {
return (
<section id={layout?.id} className="page missing">
<div className="inner">
The ACF component <strong>"{layout.__typename}"</strong> is missing. <span>🙅‍</span>
</div>
</section>
);
}
return (
<ComponentName data={layout} />
);
};
export default FlexibleLayout;
import React from 'react';
import { graphql } from 'gatsby';
import FlexibleLayout from '../../components/Acf/FlexibleLayout';
import ContentLayout from '../../components/ContentLayout/ContentLayout';
import SEO from '../../components/SEO/SEO';
export default ({ data, pageContext }) => {
const { page } = data;
const { title, seo } = page;
return (
<>
<SEO seoData={seo} uri={page.uri} />
<ContentLayout pageContext={pageContext}>
{flexibleLayout?.flexibleChildren &&
flexibleLayout?.flexibleChildren.map((layout, index) => {
return (
<FlexibleLayout
key={index}
layout={layout}
pageContext={pageContext}
/>
);
})}
</ContentLayout>
</>
);
};
export const query = graphql`
query page(
$databaseId: Int!
) {
page: wpPage(databaseId: { eq: $databaseId }) {
...PageContent
}
}
`;
export const fragments = graphql`
fragment PageContent on WpPage {
title
content
databaseId
uri
dateGmt
modifiedGmt
seo {
title
metaDesc
}
flexibleLayout {
flexibleChildren {
__typename
...Hero
...Grid
}
}
}
`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment