Skip to content

Commit

Permalink
custom HTML without <script> as server components
Browse files Browse the repository at this point in the history
  • Loading branch information
nuotsu committed Jan 19, 2025
1 parent 31269b1 commit 3f24bc7
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 56 deletions.
56 changes: 0 additions & 56 deletions src/ui/modules/CustomHTML.tsx

This file was deleted.

29 changes: 29 additions & 0 deletions src/ui/modules/CustomHTML/WithScript.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use client'

import { ComponentProps, useEffect, useRef, useState } from 'react'
import moduleProps from '@/lib/moduleProps'

/**
* @description If the code includes a <script> tag, ensure the script is re-run on each render
*/
export default function WithScript({
code,
className,
...props
}: Partial<{ code: string } & Sanity.Module> & ComponentProps<'section'>) {
if (!code) return null

const ref = useRef<HTMLElement>(null)
const [firstRender, setFirstRender] = useState(true)

useEffect(() => {
if (firstRender) {
setFirstRender(false)
} else {
const parsed = document.createRange().createContextualFragment(code)
ref.current?.appendChild(parsed)
}
}, [ref.current, code])

return <section ref={ref} {...moduleProps(props)} />
}
28 changes: 28 additions & 0 deletions src/ui/modules/CustomHTML/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import moduleProps from '@/lib/moduleProps'
import { stegaClean } from 'next-sanity'
import WithScript from './WithScript'

export default function CustomHTML({
className,
html,
...props
}: Partial<
{
className: string
html: {
code: string
}
} & Sanity.Module
>) {
if (!html?.code) return null

return html.code.includes('<script') ? (
<WithScript code={stegaClean(html.code)} {...props} />
) : (
<section
className={stegaClean(className)}
{...moduleProps(props)}
dangerouslySetInnerHTML={{ __html: stegaClean(html.code) }}
/>
)
}

0 comments on commit 3f24bc7

Please sign in to comment.