<CodePen/>

A React component for embedding CodePens

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).

jsx
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:

jsx
<CodePen user='ykadosh' slug='ExNOmZx' height={500}/>
See the Pen by Yoav Kadosh (@ykadosh) on CodePen.
Let your buddies in on this fantastic content!

A newsletter for front-end web developers

Stay up-to-date with my latest articles, experiments, tools, and much more!

Issued monthly (or so). No spam. Unsubscribe any time.