Urvashi Bangdel Rai
Hello World!
A code snippet to create a custom '+ Add item' button to add items to the top of an array.
import React, { useCallback } from 'react';
import { AddIcon } from '@sanity/icons';
import { Button, Stack } from '@sanity/ui';
import { randomKey } from '@sanity/util/content';
import { insert } from 'sanity';
const CustomArrayInput = (props) => {
const { onChange } = props;
const handleClick = useCallback(
async (event) => {
const item = {
_key: randomKey(12),
_type: 'reference',
};
// Patch the document
onChange(insert([item], 'before', [0]));
},
[onChange],
);
return (
<Stack space={3}>
<Button
icon={AddIcon}
text="Add item"
mode="ghost"
onClick={handleClick}
/>
{props.renderDefault({ ...props, arrayFunctions: () => null })}
</Stack>
);
};
export default CustomArrayInput;
import { defineField, defineType } from 'sanity';
import CustomArrayInput from '../custom/employee/StepArrayInput';
export default defineType({
name: 'myDocument',
title: 'My document',
type: 'document',
fields: [
defineField({
name: 'myArray',
type: 'array',
title: 'My array',
of: [
{
type: 'reference',
to: [{ type: 'myType' }],
},
],
components: { input: CustomArrayInput },
}),
],
});
The custom component removes the default + Add item button by setting props.arrayFunctions: () => null
.
Then, we can add our custom <Button>
component along with a click handler to do the following:
Hello World!
Senior Solutions Engineer at Sanity
Code examples using document.newDocumentOptions to hide the Create new document button at the structure level and/or disable it in the global create menu.
Go to Disable new document creation button at structure and global level with document.newDocumentOptions