Live Components

Live Components

A live code component is an interactive and dynamic element in web development that allows real-time execution, editing, and visualization of code within a web page or application. These components are particularly useful for educational purposes, documentation, and interactive coding environments.

There are libraries like Sandpack and react-live that can help you add live coding components to your MDX.


    function App() {
      const bS = { padding: '10px', fontSize: '16px', backgroundColor: 'lightgreen', border: 'none', borderRadius: '5px' };
      const hS = { fontSize: '24px', color: 'blue' };
      const [count, setCount] = React.useState(0);
      return (
        <div>
          <h1 style = {hS}>Count: {count}</h1>
          <button style={bS} 
          onClick={() => setCount(count + 1)}>Increment</button>
        </div>
      );
    }
  

Here is the code of the Live component used in this page:

import React from 'react';
import { LiveProvider, LiveEditor, LiveError, LivePreview } from 'react-live';
 
// See https://commerce.nearform.com/open-source/react-live/docs
const LiveCodeComponent = () => {
  const code = `
    function App() {
      const bS = { padding: '10px', fontSize: '16px', backgroundColor: 'lightgreen', border: 'none', borderRadius: '5px' };
      const hS = { fontSize: '24px', color: 'blue' };
      const [count, setCount] = React.useState(0);
      return (
        <div>
          <h1 style = {hS}>Count: {count}</h1>
          <button style={bS} 
          onClick={() => setCount(count + 1)}>Increment</button>
        </div>
      );
    }
  `;
 
  return (
    <LiveProvider code={code}>
      <div className="grid grid-cols-2 gap-4">
        <div>
          <LiveEditor className="font-mono" />
          <LiveError />
        </div>
        <div style={{ flex: 1 }}>
          <LivePreview className="" />
        </div>
      </div>
    </LiveProvider>
  );
};
 
export default LiveCodeComponent;