Running React code in an XBlock

Hi @abdullahnafees,

Running React from an XBlock is uncharted territory as far as I know… I’ve wanted to do a proof of concept for it but haven’t found the time. It should work fine though - just follow the usual XBlock tutorials and make sure to add the React JS as one of the JS libraries required by your XBlock’s HTML Fragment, and then include an empty <div> in the HTML of your fragment, and use the initialize_js code to point to some JS like this:

function initializeMyReactXBlock(runtime, element, configuration) {
    const root = ReactDOM.createRoot(element);  // or maybe in a child div of element
    root.render(<h1>Hello, world!</h1>);
}

Of course, if you want to use JSX as in this example you’ll need to use some tool like TypeScript that can transpile the JSX to React.createElement(...) calls.

For a vaguely similar example, refer to the drag and drop v2 xblock - it uses a virtual DOM just like React does:

1 Like