Photo by Airam Dato-on on Unsplash

Use tables in sanity cms

December 9th, 2020

Sanity is a great headless CMS that have gained a lot of traction the last years. A lot of sites on the web are now running on Sanity, including this one right here :)

One thing I could not find in a fresh install, was regular tables to have in the bodytext. Luckily one of the great features of sanity is that it is easily extendable. It has a good list of plugins https://www.sanity.io/plugins

The most relevant for us is the datatable plugin

https://www.sanity.io/plugins/sanity-plugin-datatable

npm install -g @sanity/cli  # sanity cli required
cd web
sanity install datatable

The different content-types to use in bodytext is defined in an array in bodyportableText.js, and in here we must add the new type for table:

// studio/schemas/objects/bodyPortableText.js
...
{
  type: 'mainImage',
  options: {hotspot: true}
},
{
  type: 'table',
  title: 'Table'
}

Next step is to extend the serializer with some react to make it render the data as a table.

// web/src/components/serializers.js
...
const serializers = {
  types: {
    authorReference: ({node}) => <span>{node.author.name}</span>,
    mainImage: Figure,
    table: ({node = {}}) => {
      let {rows} = node
      const firstRow = rows.shift();

      return <table>
         <thead>
           <tr>
            {firstRow.cells.map((cell, index) => {
                  return <th key={index}>{cell}</th>
            })}
          </tr>
        </thead>
        <tbody>
        {rows.map((row, index) => {
          return <tr key={index}>
            {row.cells.map((cell, index) => {
              return <td key={index}>{cell}</td>
            })}
          </tr>
        })}
        </tbody>
      </table>
    }
  }
}

export default serializers

Thats it, a really simple solution. Go look at my commit for the whole overview.

If you need proof:

NameNumber
Agent Cooper123456789
Audry Horne987654321
Bob654987321