How to access the slug of a reference to a route in a CTA object within a hero element
2 replies
Last updated: Jun 29, 2022
I
Hi!Is there an easy way to access the slug of a reference to a route?
I'm trying to set up support for internal links within a cta object, that can be added to a hero element.
(I've added more info inside this thread).
I'm trying to set up support for internal links within a cta object, that can be added to a hero element.
(I've added more info inside this thread).
Jun 28, 2022, 3:07 PM
I
The cta-object schema looks like this:
And the hero schema looks like this:
The Cta object looks like this, but I can't access route.slug from here without some tweaking. How do I expose the slug:
export default { title: "Call to action", name: "cta", type: "object", validation: (Rule) => Rule.custom( (fields = {}) => !fields.route || !fields.link || "Only one link type is allowed" ), fieldsets: [ { title: "Link", name: "link", }, ], fields: [ { title: "Tittel", name: "title", type: "string", }, { title: "Intern lenke", description: "Bruk dette feltet for å lenke til en side som tilhører dette nettstedet.", name: "route", type: "reference", to: [{ type: "route" }], fieldset: "link", }, { title: "Ekstern lenke", name: "link", type: "url", fieldset: "link", }, { title: 'Åpne i ny fane?', name: 'blank', type: 'boolean', fieldset: "link", } ], };
export default { type: "object", name: "hero", title: "Hero", fields: [ { name: "heading", type: "string", title: "Heading", }, { name: "tagline", type: "portableText", title: "Tagline", }, { name: "backgroundImage", type: "image", title: "Background image", options: { hotspot: true, }, }, { name: "imagePlacement", type: "string", title: "Bildeplassering", options: { list: [ {title: "Venstre", value: "last"}, {title: "Høyre", value: "first"} ] } }, { name: "ctas", type: "array", title: "Call to actions", of: [ { title: "Call to action", type: "cta", }, ], }, ], };
function Cta(props) { const { title, route, link } = props; if (route && route.slug && route.slug.current) { return ( <Link href={`/${route.slug.current}`}>{title}</Link> ); } if (link) { return <a href={link}>{title}</a>; } return <a>{title}</a>; } Cta.propTypes = { title: PropTypes.string.isRequired, route: PropTypes.shape({ slug: PropTypes.shape({ current: PropTypes.string, }), }), link: PropTypes.string, }; export default Cta;
Jun 28, 2022, 3:07 PM
I
Nvm. I manage to solve it by dereferencing the route reference inside my page/[slug].js query
page-> { content[] { ctas[] { ..., route->{slug} } } }
Jun 29, 2022, 2:28 PM
Sanity– build remarkable experiences at scale
The Sanity Composable Content Cloud is the headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.