πŸ‘€ Our most exciting product launch yet πŸš€ Join us May 8th for Sanity Connect

How to create a reference mark in Sanity using block-tools and a portable text schema.

4 replies
Last updated: Feb 21, 2022
I'm importing a bunch of articles from another platform to Sanity using
sanity/block-tools
. References between articles are given by the following type.
export default {
  name: "hjelpeartikkelLink",
  type: "object",
  title: "Lenke til en hjelpeartikkel",
  fields: [
    {
      name: "reference",
      type: "reference",
      to: [{ type: "hjelpeartikkel" }],
      validation: (Rule) => Rule.required().error("...")
    }
  ]
};
My deserialize method has a match on relevant `href`'s given
a
-tags, and needs to return a
block({...})
. However, I can't seem to figure out what
{...}
should be in order to give me a span with a reference mark. Am I coming at this right? How do I create a reference?
Jan 24, 2022, 2:14 PM
I converted some html with a tags into annotations with this script: https://gist.github.com/d4rekanguok/8a6c698d16ef6666196ae028c04066bc
If you have a portable text schema like this:

{
  name: 'content',
  type: 'array',
  of: [{
    type: 'block',
    marks: {
      annotations: [
        {
          name: 'linkInternal',
          type: 'object',
          fields: [{
            name: 'target',
            type: 'reference',
            to: [{ type: 'page' }]
          }]
        }
      ]
    }
  }]
}
then you should be able to create a reference by creating an object like this:


/* other stuff */
return {
  type: '__annotation',
  markDef: {
    // extract properties from <a /> and
    // get the sanity document id
    _type: 'linkInternal',
    _key: randomKey(12),
    target: {
      _type: 'reference',
      _ref: relevantDocumentId
    },
  },
  children: next(el.childNodes)
}
Have been awhile so let me know if it works
πŸ˜…
Jan 24, 2022, 3:27 PM
Using this, it seems I was able to make it work! Tyvm πŸ™‚
Jan 24, 2022, 4:56 PM
I'm trying to do this for links but I'm having issues. Does this look wrong to you?
export const link = (url, children) => {
  const key = randomKey(12);
  return ({
    _type: "__annotation",
    markDef: {
      _type: "link",
      _key: key,
      href: url
    },
    children: children?.map(it => ({ ...it, marks: [...(it?.marks || []), key] }))
  });
}

Feb 21, 2022, 2:12 PM
In deserialization rules:
if (tagName === "a") {
  return link(el.href, next(el?.childNodes));
}

Feb 21, 2022, 2:13 PM

Sanity– build remarkable experiences at scale

Sanity is a 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.

Was this answer helpful?