React Runner

1.0.5 · active · verified Tue Apr 21

React Runner is a JavaScript library designed for executing and previewing live React code directly within a web application. Currently stable at version 1.0.5, it provides components and hooks to dynamically run arbitrary React code snippets, supporting modern JavaScript features like class fields, arrow functions for event handlers, and `import` statements. Unlike alternatives like `react-live` which use Bublé, React Runner leverages Sucrase for transpilation, offering broader compatibility with contemporary syntax and TypeScript without enforcing strict coding patterns. It facilitates scenarios such as interactive documentation, code playgrounds, and component development environments, offering features like multi-file code execution and server-side rendering support. While there isn't an explicit release cadence mentioned, the 1.x.x versioning implies ongoing maintenance within this major branch.

Common errors

Warnings

Install

Imports

Quickstart

Illustrates dynamic execution of React code, demonstrating how to provide external components and manage imports within the `scope` for a live preview, including state and interaction.

import React, { useState } from 'react';
import { Runner } from 'react-runner';

const initialCode = `
  import { Button } from './MyComponents';

  function MyLiveComponent() {
    const [count, setCount] = React.useState(0);
    return (
      <div style={{ padding: 20, border: '1px solid #eee' }}>
        <h2>Live Counter: {count}</h2>
        <Button onClick={() => setCount(c => c + 1)}>Increment</Button>
      </div>
    );
  }
  export default MyLiveComponent;
`;

const MyButton = ({ children, onClick }) => (
  <button style={{ background: 'blue', color: 'white', padding: '10px 15px', borderRadius: '5px', border: 'none', cursor: 'pointer' }} onClick={onClick}>
    {children}
  </button>
);

const App = () => {
  const [code, setCode] = useState(initialCode);
  const scope = {
    React,
    useState,
    Button: MyButton,
    import: {
      './MyComponents': { Button: MyButton }
    }
  };

  const handleRendered = () => console.log('Live component rendered!');

  return (
    <div>
      <h3>Edit the code below:</h3>
      <textarea
        value={code}
        onChange={(e) => setCode(e.target.value)}
        rows={15}
        cols={80}
        style={{ width: '100%', minHeight: '200px', marginBottom: '20px', fontFamily: 'monospace' }}
      />
      <h3>Live Preview:</h3>
      <Runner code={code} scope={scope} onRendered={handleRendered} />
    </div>
  );
};

export default App;

view raw JSON →