Skip to content

Commit

Permalink
Ensure any <scripts> are re-run after each render in Custom HTML module
Browse files Browse the repository at this point in the history
  • Loading branch information
Mitchell Christ committed Aug 5, 2024
1 parent 09b83f4 commit fd78037
Showing 1 changed file with 30 additions and 7 deletions.
37 changes: 30 additions & 7 deletions src/ui/modules/CustomHTML.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
'use client'

import uid from '@/lib/uid'
import { stegaClean } from '@sanity/client/stega'
import { useEffect, useRef, useState } from 'react'

export default function CustomHTML({
className,
Expand All @@ -13,13 +16,33 @@ export default function CustomHTML({
}
}
>) {
const ref = useRef<HTMLElement>(null)
const [firstRender, setFirstRender] = useState(true)

if (!html?.code) return null

return (
<section
id={uid(props)}
className={stegaClean(className)}
dangerouslySetInnerHTML={{ __html: html.code }}
/>
)
if (!html.code.includes('<script'))
return (
<section
id={uid(props)}
className={stegaClean(className)}
dangerouslySetInnerHTML={{ __html: stegaClean(html.code) }}
/>
)

// if includes <script> tag, ensure script is re-run on each render

useEffect(() => {
if (firstRender) {
setFirstRender(false)
} else {
const parsed = document
.createRange()
.createContextualFragment(stegaClean(html.code))

ref.current?.appendChild(parsed)
}
}, [ref.current, html.code])

return <section ref={ref} id={uid(props)} className={stegaClean(className)} />
}

0 comments on commit fd78037

Please sign in to comment.