Skip to content

Instantly share code, notes, and snippets.

@Aberratio
Last active October 27, 2022 04:30
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 Aberratio/fed99b6961850468a140c0fe6c39ce9c to your computer and use it in GitHub Desktop.
Save Aberratio/fed99b6961850468a140c0fe6c39ce9c to your computer and use it in GitHub Desktop.
[Sanity.io v2] Dynamically changes the icons assigned to the icons selected in the childObject answers array depending on the type of the selected childObject and the showCorrectnes state of the parent object.

Sanity.io - refer to the document in the preview of the object.

Dynamically changes the icons assigned to the icons selected in the childObject answers array depending on the type of the selected childObject and the showCorrectnes state of the parent object.

first example of use

showCorrectness: false

image

second example of use

showCorrectness: true answer1 - isCorrect: true answer2 - isCorrect: false

image

import React from 'react';
import ChildObjectView from './ChildObjectView';
export default {
name: 'childObject',
title: 'Child Object',
type: 'object',
fields: [
{
title: 'Text',
name: 'text',
type: 'string',
},
{
title: 'Is correct',
name: 'isCorrect',
type: 'boolean',
hidden: ({ document }) => {
return !document.showCorrectness;
},
validation: (Rule) =>
Rule.custom((correctness, { document }) => {
if (!document.showCorrectness) {
return true;
}
return 'Correctness required';
}),
},
],
preview: {
select: {
isCorrect: 'isCorrect',
text: 'text',
},
prepare(child) {
return {
title: child.text,
media: <ChildObjectView isCorrect={child.isCorrect} />,
};
},
},
};
import React from 'react';
import { withDocument } from 'part:@sanity/form-builder';
const ChildObjectView = (props) => {
const PARENT_ICON = {
correct: '✅',
incorrect: '❌',
neutral: '🔵',
};
let parentIcon = PARENT_ICON.neutral;
if (props.document.showCorrectness) {
parentIcon = props.isCorrect ? PARENT_ICON.correct : PARENT_ICON.incorrect;
}
return <p>{parentIcon}</p>;
};
export default withDocument(ChildObjectView);
export default {
name: 'parentObject',
title: 'Parent',
type: 'document',
fields: [
{
name: 'showCorrectness',
title: 'Show Correctness',
type: 'boolean',
},
{
name: 'answers',
title: 'Answers',
type: 'array',
of: [{ type: 'childObject' }],
},
],
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment