React Live Playground
Look down, you can preview and edit this React code in real time! 🤯
Pretty cool, right?
Instructions and Sample code
You can get this exact thing in your React project, too – a blog, documentation site, whatever!
First install the react-live-playground NPM package to a React project. Then, simply import it as a regular component and use it as you wish. Make sure to include pass the code
prop as a string, which can be either pure JSX, a pure functional component, or a React class component. For the full list of props, see the package README!
Sample
import ReactLivePlayground from "react-live-playground"
import theme from "prism-react-renderer/themes/ultramin"
export const code = `
function Button() {
return (
<div style={{display: 'flex', justifyContent: 'center'}}>
<button
onClick={() => alert("Hello World!")}
style={{
border: 'none',
textAlign: 'center',
boxSizing: 'border-box',
textDecoration: 'none',
padding: '10px 40px',
cursor: 'pointer',
background: '#D4AF37',
background: 'linear-gradient(to bottom, #D4AF37 0%, #C5A028 100%)',
boxShadow: '0 4px 6px rgba(50, 50, 93, .11), 0 1px 3px rgba(0, 0, 0, .08)',
color: 'white',
fontSize: '18px', fontWeight: '700',
borderRadius: '25px'
}}
>
Gold button
</button>
</div>
)
}
`.trim()
<ReactLivePlayground code={code} theme={theme} />
Note: This sample from above was written in a
.mdx
file, which is an extension of.md
files that lets you use JSX in your Markdown.
I recently refactored gatsby-personal-starter-blog to include MDX. If you also have a Gatsby blog, it’s a cool feature to have to show off React components in your blog posts. React Live Playground can be used in a regular React .js
file just fine though!
How and why I built this
The good folks over at Formidabble make some pretty dope tools. They made component-playground and more recently react-live, which I wrapped to make this component.
I made this component because although the React Live Demo (demo folder) is nice, having the preview side-by-side with the code is too narrow for my blog. Also, to use React Live out-of-the-box, you have to include 4 separate components: <LiveProvider />
. <LiveEditor />
. <LiveError />
, and <LivePreview />
.
I’m a believer that things should just work, and making this component solved this problem for me. I hope it might be helpful for you as well!
⚛