Skip to content

Instantly share code, notes, and snippets.

@pzi
Created September 7, 2020 03:16
Show Gist options
  • Save pzi/48e3d84a8d2388edcb7878c0c88abf65 to your computer and use it in GitHub Desktop.
Save pzi/48e3d84a8d2388edcb7878c0c88abf65 to your computer and use it in GitHub Desktop.
FAQ Document & block content section for Sanity
// add to blockContent array
{
type: 'faqSection',
},
import { FaQuestion } from 'react-icons/fa';
import links from '../objects/links';
export default {
title: 'Questions & Answers',
name: 'faq',
type: 'document',
icon: FaQuestion,
fields: [
{
title: 'Question',
name: 'question',
type: 'string',
validation: (Rule) => Rule.required(),
},
{
title: 'Answer',
name: 'answer',
type: 'array',
of: [
{
title: 'Block',
type: 'block',
styles: [{ title: 'Normal', value: 'normal' }],
lists: [
{ title: 'Bullet', value: 'bullet' },
{ title: 'Number', value: 'number' },
],
marks: {
decorators: [
{ title: 'Strong', value: 'strong' },
{ title: 'Emphasis', value: 'em' },
],
annotations: [...links],
},
},
],
validation: (Rule) => Rule.required(),
},
],
preview: {
select: {
title: 'question',
subtitle: 'answer',
},
},
};
const faqSection = `
questions[]-> {
...,
answer[] {
...,
markDefs[] {
...,
${internalLink}
}
}
},
`;
const pageFields = `
title,
description,
slug,
body[] {
...,
"asset": asset->,
${faqSection}
markDefs[] {
...,
${internalLink},
}
}
`;
import { FaQuestion } from 'react-icons/fa';
export default {
title: 'FAQ Section',
name: 'faqSection',
type: 'object',
icon: FaQuestion,
fields: [
{
title: 'Questions',
name: 'questions',
type: 'array',
description: 'Choose the questions to display in this block.',
of: [{ type: 'reference', title: 'Question', to: [{ type: 'faq' }] }],
validation: (Rule) => [Rule.unique()],
},
],
preview: {
select: {
questions: 'questions',
},
prepare({ questions }) {
let subtitle = '';
if (questions) {
const suffix = questions.length !== 1 ? 's' : '';
subtitle = `${questions.length} question${suffix} selected`;
}
return {
title: 'Frequently Asked Questions',
subtitle,
};
},
},
};
import BlockContent, { BlockContentProps } from '@sanity/block-content-to-react';
export const serializers: BlockContentProps['serializers'] = {
types: {
faqSection: (props: any) => (
<>
{props.node.questions.map((question: any) => (
<section key={question._id}>
<h3>{question.question}</h3>
<BlockContent blocks={question.answer} serializers={serializers} />
</section>
))}
</>
),
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment