Skip to content

Instantly share code, notes, and snippets.

@thibaudcolas
Created May 7, 2024 21:09
Show Gist options
  • Save thibaudcolas/dae25206721033f64a83a1a3f66a4a8e to your computer and use it in GitHub Desktop.
Save thibaudcolas/dae25206721033f64a83a1a3f66a4a8e to your computer and use it in GitHub Desktop.
Next.js + GraphQL + Wagtail dynamic page type routing
import { gql } from 'graphql-tag';
// Generic `page` query, by site and URL path (unique per site).
export const pageQuery = gql`
query ($urlPath: String, $siteId: ID, $previewToken: String) {
site(id: $siteId) {
id
page(urlPath: $urlPath, token: $previewToken) {
...getBaseContentPageFields
}
}
}
${BaseContentPageFragment}
`;
// Fragment which caters for the data of different page types.
export const BaseContentPageFragment = gql`
fragment getBaseContentPageFields on PageInterface {
id
... on HomePage {
${BasePageFields}
${BaseContentFields}
${BannerImageFields}
${BannerSearchFields}
}
... on ContentPage {
${BasePageFields}
${BaseContentFields}
}
... on LandingPage {
${BasePageFields}
${BaseContentFields}
${BannerImageFields}
}
... on CollectionPage {
${BasePageFields}
${BannerImageFields}
contentBeforeCollection {
...getStreamFieldBlock
}
contentAfterCollection {
...getStreamFieldBlock
}
...getBaseCollectionPageFields
}
}
${StreamFieldBlock}
${BaseCollectionPageFields}
`;
// Render a different component based on the page’s `contentType`.
const Page: NextPage<PageProps> = ({ page }: InferGetStaticPropsType<typeof getStaticProps>) => {
// Render page based of its contentType
const { contentType } = page;
switch (contentType) {
case 'core.ContentPage':
return <ContentPage page={page} />;
case 'core.LandingPage':
return <LandingPage page={page} />;
case 'core.HomePage':
return <HomePage page={page} />;
case 'core.CollectionPage':
return <CollectionPage page={page} />;
default:
throw new Error(`${contentType} is not a valid content type.`);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment