There are various ways to embed CodePens, but the recommended way is to use HTML + the CodePen embed script.
The issue is that the script runs as soon as it loads, converting all elements
with the class name .codepen
into CodePen embeds. So you can't just load it at the <head/>
of the document and then add the CodePen embeds later.
We can use React's useEffect
hook to load the script after the component has
been mounted (and remove it when it unmounts).
export const CodePen = ({ user, slug, height }) => {
useEffect(() => {
const script = document.createElement('script');
script.src = 'https://cpwebassets.codepen.io/assets/embed/ei.js';
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
};
}, []);
return (
<div className='codepen' data-height={height} data-theme-id='dark' data-default-tab='result'
data-slug-hash={slug} data-editable='true' data-user={user}
style={{ height }}>
// Show a spinner or some fallback content here
</div>
);
};
And here's an example of how to use it:
<CodePen user='ykadosh' slug='ExNOmZx' height={500}/>