The problem can be seen here
I built a site using Sanity headless CMS and GatsbyJS on the frontend.
I'm querying URLs dynamically so that it can be rendered inside the src
attribute of an </iframe>
The problem is when the user adds an URL containing &
, pretty common for Google Calendar's embed code.
With &
The link no longer works and the calendar breaks (goes blank). Unless I hardcode it directly in the src
which is exactly what we want to avoid.
How can I mitigate/escape this issue and have it so I can render the URL accordingly?
I've looked into encodeURI
, encodeURIComponent
, even tried this custom function:
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
No dice...
- Looking for a client-side JS solution or backend solution, if possible to do so, inside Sanity's ecosystem
My current implementation
// sanity schema
export default {
type: 'document',
title: 'Google Calendar',
name: 'calendar',
fields: [
{
type: 'string',
name: 'Title',
},
{
type: 'url',
name: 'URL',
validation: (Rule) => Rule.required(),
},
],
};
//gastby
export default function GoogleCalendar() {
const { calendar } = useStaticQuery(graphql`
query {
calendar: allSanityCalendar {
nodes {
URL
Title
}
}
}
`);
if (!calendar.nodes.length) return null;
return (
<>
<div>
{calendar.nodes.map((node) => (
<iframe
src={node.URL}
id="test"
title={node.Title}
width="100%"
height="1000px"
async
/>
))}
</div>
</>
);
}
Here's a sandbox illustrating the issue: https://stackblitz.com/edit/iframe-dynamic-src