Skip to content

Instantly share code, notes, and snippets.

@Grsmto
Last active June 23, 2021 16:54
Show Gist options
  • Save Grsmto/cc4db257d05898ca60a9572511fa9bcf to your computer and use it in GitHub Desktop.
Save Grsmto/cc4db257d05898ca60a9572511fa9bcf to your computer and use it in GitHub Desktop.
Sanity custom ArrayFunctions component to limit length of Arrays
// Simple implementation of https://github.com/sanity-io/sanity/blob/21af6baffe88d57db32d0a05e048ef7d3d671523/packages/%40sanity/form-builder/src/inputs/ArrayInput/ArrayFunctions.tsx
import React from "react";
import DropDownButton from "part:@sanity/components/buttons/dropdown";
import Button from "part:@sanity/components/buttons/default";
import ButtonGrid from "part:@sanity/components/buttons/button-grid";
import styles from "./styles/ArrayInput.css";
export default class ArrayFunctions extends React.Component {
handleDropDownAction = (menuItem) => {
this.handleInsertItem(menuItem.type);
};
handleAddBtnClick = () => {
this.handleInsertItem(this.props.type.of[0]);
};
handleInsertItem = (type) => {
const { onCreateValue, onAppendItem } = this.props;
const item = onCreateValue(type);
onAppendItem(item);
};
renderSelectType() {
const items = this.props.type.of.map((memberDef) => ({
title: memberDef.title || memberDef.type.name,
type: memberDef,
}));
return (
<DropDownButton
inverted
items={items}
onAction={this.handleDropDownAction}
>
Add
</DropDownButton>
);
}
render() {
const { type, readOnly, children, value } = this.props;
const maxLength = type.validation[0]._rules.find(
(rule) => rule.flag === "max"
);
if (maxLength && value && value.length >= maxLength.constraint) {
return null;
}
if (readOnly) {
return null;
}
return (
<div className={styles.functions}>
<ButtonGrid align="start">
{type.of.length === 1 ? (
<Button inverted onClick={this.handleAddBtnClick}>
Add
</Button>
) : (
this.renderSelectType()
)}
{children || null}
</ButtonGrid>
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment