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:
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
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.
Hi @abdullahnafees could you add React to your Xblock? I need to do the same but I couldn’t able to do it yet
Greetings all, curious if there are any updates on this topic? Has anyone succeeded in adding ReactJS for multiple roles (student, staff, et al)?
Hey folks, I got time this week to put together a proof of concept that shows how to use React in an XBlock: GitHub - open-craft/xblock-react: An example of a React-based XBlock (React student_view, React studio_view, react-intl)
It’s based on the XBlock cookiecutter (which, sadly, turned out to be broken). It works, integrates with Tutor, uses React 18 for both student_view
and studio_view
, is compatible with the new Studio unit MFE page, is fully type-safe (TypeScript), and uses react-intl
for i18n. It does not support Paragon (as its SCSS is not available and I found that Paragon has a bunch of bugs that make it unsuitable).
I plan to apply some of these changes to the cookiecutter template if they’re well received.