-
-
Notifications
You must be signed in to change notification settings - Fork 63
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
custom HTML without
<script>
as server components
- Loading branch information
Showing
3 changed files
with
57 additions
and
56 deletions.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)} /> | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) }} | ||
/> | ||
) | ||
} |