Watch a live product demo 👀 See how Sanity powers richer commerce experiences

Adding Multiple References to a Reference List

5 replies
Last updated: Jan 21, 2022
Hi everyone! I am using an array of references that may be used to select various itens. Thinking in terms of usability, I would like to know if there's a way to facilitate this multiple selection. At the moment, user needs to click 'add item', then type or click on the arrow down to see some options, select one, and then repeat this proccess for each subsequent selection; I was thinking about a solution involving checkboxes, inside the dropdown or even separatedly, but in a way that user can see the available options and just clicks on the ones he wants. So my question, is there currently a way that I can have something similar to this?I'm attaching an example to provide more clarity. Thanksss
Jan 17, 2022, 11:36 AM
Hi Racheal! Thanks for the responseYess, the UI for the array of strings looks exactly what I need! But in my case I really need to select references, sorry that with the image I posted I ended up misguiding my intentions haha
Isn't there a way to achieve a similar UI using array of references?
Jan 18, 2022, 12:16 AM
Not out of the box, but you could do it with a custom input component. I played around with it and got this to work:
{
      name: 'ReferenceMultiSelect',
      title: 'Country',
      type: 'array',
      of: [
        {
         type: 'reference',
         to: { type: 'country'}
        }
      ],
      inputComponent: ReferenceSelect
    }

//ReferenceSelect.js

import React, { useEffect, useState } from 'react'
import { Card, Flex, Checkbox, Box, Text } from '@sanity/ui'
import { FormField } from '@sanity/base/components'
import PatchEvent, {set, unset} from '@sanity/form-builder/PatchEvent'
import { useId } from "@reach/auto-id" 
import { studioClient } from '../../src/utils/studioClient'

const ReferenceSelect = React.forwardRef((props, ref) => {
  const [countries, setCountries] = useState([])

  useEffect(() => {
    const fetchCountries = async () => {
      await studioClient
        .fetch(`*[_type == 'country']{
          _id,
          title
        }`)
        .then(setCountries)
    }

    fetchCountries()
  }, []) 

  const { 
    type,         // Schema information
    value,        // Current field value
    readOnly,     // Boolean if field is not editable
    markers,      // Markers including validation rules
    presence,     // Presence information for collaborative avatars
    compareValue, // Value to check for "edited" functionality
    onFocus,      // Method to handle focus state
    onBlur,       // Method to handle blur state  
    onChange,      // Method to handle patch events,
  } = props

  const handleClick = React.useCallback(
    (e) => {
      const inputValue = {
        _key: e.target.value.slice(0, 10),
        _type: 'reference',
        _ref: e.target.value
      }
      
      if(value) {
        if(value.some(country => country._ref === inputValue._ref)) {
          onChange(PatchEvent.from(set(value.filter(item => item._ref != inputValue._ref))))
        } else {
          onChange(PatchEvent.from(set([...value, inputValue])))
        }
      } else {
        onChange(PatchEvent.from(set([inputValue])))
      }
    },
    [value]
  )

  const inputId = useId()

	return (
    <FormField
      description={type.description}  // Creates description from schema
      title={type.title}              // Creates label from schema title
      __unstable_markers={markers}    // Handles all markers including validation
      __unstable_presence={presence}  // Handles presence avatars
      compareValue={compareValue}     // Handles "edited" status
      inputId={inputId}               // Allows the label to connect to the input field
      readOnly={readOnly}
    >
      {
        countries.map(country => (
          <Card padding={2}>
            <Flex align="center">
              <Checkbox 
                id="checkbox" 
                style={{display: 'block'}} 
                onClick={handleClick}
                value={country._id}
                checked={value ? value.some(item => item._ref === country._id) : false}
              />
              <Box flex={1} paddingLeft={3}>
                <Text>
                  <label htmlFor="checkbox">{country.title}</label>
                </Text>
              </Box>
            </Flex>
          </Card>
        ))
      }
    </FormField>
	)
})

export default ReferenceSelect
But if you want to go with out of the box option, you can just use the following and select from a list:

{
      name: 'countries',
      title: 'Country',
      type: 'array',
      of: [
        {
         type: 'reference',
         to: { type: 'country'}
        }
      ],
    }
Jan 18, 2022, 4:07 AM
Not out of the box, but you could do it with a custom input component. I played around with it and got this to work:
{
      name: 'ReferenceMultiSelect',
      title: 'Country',
      type: 'array',
      of: [
        {
         type: 'reference',
         to: { type: 'country'}
        }
      ],
      inputComponent: ReferenceSelect
    }

//ReferenceSelect.js

import React, { useEffect, useState } from 'react'
import { Card, Flex, Checkbox, Box, Text } from '@sanity/ui'
import { FormField } from '@sanity/base/components'
import PatchEvent, {set, unset} from '@sanity/form-builder/PatchEvent'
import { useId } from "@reach/auto-id" 
import { studioClient } from '../../src/utils/studioClient'

const ReferenceSelect = React.forwardRef((props, ref) => {
  const [countries, setCountries] = useState([])

  useEffect(() => {
    const fetchCountries = async () => {
      await studioClient
        .fetch(`*[_type == 'country']{
          _id,
          title
        }`)
        .then(setCountries)
    }

    fetchCountries()
  }, []) 

  const { 
    type,         // Schema information
    value,        // Current field value
    readOnly,     // Boolean if field is not editable
    markers,      // Markers including validation rules
    presence,     // Presence information for collaborative avatars
    compareValue, // Value to check for "edited" functionality
    onFocus,      // Method to handle focus state
    onBlur,       // Method to handle blur state  
    onChange,      // Method to handle patch events,
  } = props

  const handleClick = React.useCallback(
    (e) => {
      const inputValue = {
        _key: e.target.value.slice(0, 10),
        _type: 'reference',
        _ref: e.target.value
      }
      
      if(value) {
        if(value.some(country => country._ref === inputValue._ref)) {
          onChange(PatchEvent.from(set(value.filter(item => item._ref != inputValue._ref))))
        } else {
          onChange(PatchEvent.from(set([...value, inputValue])))
        }
      } else {
        onChange(PatchEvent.from(set([inputValue])))
      }
    },
    [value]
  )

  const inputId = useId()

	return (
    <FormField
      description={type.description}  // Creates description from schema
      title={type.title}              // Creates label from schema title
      __unstable_markers={markers}    // Handles all markers including validation
      __unstable_presence={presence}  // Handles presence avatars
      compareValue={compareValue}     // Handles "edited" status
      inputId={inputId}               // Allows the label to connect to the input field
      readOnly={readOnly}
    >
      {
        countries.map(country => (
          <Card padding={2}>
            <Flex align="center">
              <Checkbox 
                id="checkbox" 
                style={{display: 'block'}} 
                onClick={handleClick}
                value={country._id}
                checked={value ? value.some(item => item._ref === country._id) : false}
              />
              <Box flex={1} paddingLeft={3}>
                <Text>
                  <label htmlFor="checkbox">{country.title}</label>
                </Text>
              </Box>
            </Flex>
          </Card>
        ))
      }
    </FormField>
	)
})

export default ReferenceSelect
Jan 18, 2022, 4:07 AM
Amaaazing! It worked perfectly! That seemed like a lot of work, much much thanks! My UI looks way better now thanks to you haha Have all the best!
Jan 20, 2022, 2:41 AM
Glad it worked for you!
Jan 21, 2022, 3:54 PM

Sanity– build remarkable experiences at scale

The Sanity Composable Content Cloud is the modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Related answers

Get more help in the community Slack

TopicCategoriesFeaturedRepliesLast Updated
After adding the subtitle and running this code npm run graphql-deploy It does nothingSep 15, 2020
how to limit a reference to just one entry in Studio reference input side versus the default as-many-entries-as-you-fill-in-an-array...Sep 18, 2020
Is it possible to fetch more than one "_type" using GROQ?Nov 2, 2020
I want to add a view with the Structure builder (S.view.component) where I list similar documents based on the title. What...Sep 23, 2020
Is there a structure builder example where the format of each preview for the document list is modified?Feb 3, 2021
I have an array of references to a country schema type but it always just returns NULL values for meJan 30, 2021
Hi, I need help with a query for getting the url of an image asset. Here is what I've been trying, but I only get the _ref...Dec 1, 2020
Sanity UI looks brilliant :smiley: Is something like the current date picker possible at the moment? I’m not sure if anicon...Dec 21, 2020
Hey everyone. I have been coding and may have potentially accidentally deleted something. Does anyone know how to resolve...Dec 26, 2020
Hello everyone and happy new year :raised_hands::skin-tone-2:, I have a problem with outputting Portable Text :disappointed:...Jan 1, 2021

Related contributions

Clean Next.js + Sanity app
- Template

Official(made by Sanity team)

A clean example of Next.js with embedded Sanity ready for recomposition.

Cody Olsen
Go to Clean Next.js + Sanity app

Blog with Built-in Content Editing
- Template

Official(made by Sanity team)

A Sanity-powered blog with built-in content editing and instant previews.

Go to Blog with Built-in Content Editing