Running React code in an XBlock

I want to run React code for the author view of an XBlock. Is it possible? I am a complete beginner to the Open edX code base and XBlock-SDK and I have just installed the devstack.

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

hey guys, coincidentally my colleagues at Querium Corp just happen to also be at work on this as well. looking forward to seeing what anyone has to add :smiley:

Hi @abdullahnafees and @braden ,

I’m also working on this very thing today: Trying to get a React app to run in a div, but inside the student view of my xblock. Any other tips/news here would be much appreciated.

@braden Thank you for such a detailed and on-point response. I will test it on my end and get back to you. Hopefully, I will have something helpful to add to the discussion.

1 Like