Unlock seamless workflows and faster delivery with our latest releases – get the details

Add items to top of array with custom '+ Add item' button

By Urvashi Bangdel Rai & Tom Smith

A code snippet to create a custom '+ Add item' button to add items to the top of an array.

Custom array input component

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;

Using the custom component

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:

  • Patch the document
  • Insert the value at the top of the array

Contributors

Other schemas by authors