How to expand a reference in a link component in React Portabletext serializers
8 replies
Last updated: Oct 15, 2021
N
Hello hello! Quick question:I have this cool link component which can link to internal documents or to external URLS:
Now I’m stuffing that into this blockContent component:
Now uhm I’m trying to figure out how to use that in the serializers of React Portabletext:
which gives me this on the console:
Is there a way to expand this reference ..?
import { HiLink } from "react-icons/hi"; import { LINK_REFERENCES } from "../config"; export default { name: "link", type: "object", title: "Link", blockEditor: { icon: HiLink, }, description: "You shall only use one of these – trust me :)", fields: [ { name: "external", type: "url", title: "URL", validation: (Rule) => Rule.uri({ scheme: ["http", "https", "tel", "mailto"], allowRelative: true, }), hidden: ({ parent, value }) => !value && parent?.internal, }, { name: "internal", type: "reference", to: LINK_REFERENCES.map((type) => ({ type })), hidden: ({ parent, value }) => !value && parent?.external, }, ], };
export default { title: "Block Content", name: "blockContent", type: "array", of: [ { title: "Block", type: "block", styles: [ ... ], lists: [ ... ], marks: { decorators: [ ... ], annotations: [ { type: "link", }, ], }, }, { type: "figure", }, { type: "attachment", }, ], };
const link = ({ children, mark }) => { console.log({ mark }); return <Link link={mark}>{children}</Link>; };
{ "mark": { "_key": "e602ef2fe9a9", "_type": "link", "internal": { "_ref": "127465e0-3999-4a66-b54d-fa42b0f020ce", "_type": "reference" } } }
Oct 15, 2021, 1:58 PM
N
ohh I guess I have to do that in the query
Oct 15, 2021, 2:04 PM
N
hold on 🔮
Oct 15, 2021, 2:04 PM
N
Got it thanks for rubber ducking 🙂
Oct 15, 2021, 2:23 PM
B
user N
Could you share your query? I am having the same problem, only I can dereference anything but links in markdefs for some reasonOct 15, 2021, 3:40 PM
N
Oh yes sure!
Oct 15, 2021, 6:35 PM
N
_type == "richText" => { _type, _key, headline, "content": content[] { ..., markDefs[] { ..., _type == "link" => { "internal": internal->slug.current, external } }, _type == "attachment" => { ..., asset-> { extension, mimeType, size, url, "name": originalFilename, "createdAt": _createdAt, "updatedAt": _updatedAt, }, author->, }, } }
Oct 15, 2021, 6:35 PM
N
this is the complete query for blockContent in our setup. The interesting part is probably:
markDefs[] { ..., _type == "link" => { "internal": internal->slug.current, external } },
Oct 15, 2021, 6:36 PM
B
Huh, thanks! For some reason my reference -> won't work. Thanks!
Oct 15, 2021, 6:58 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.