Home > database >  Load a React component at runtime from a plain JSX external script
Load a React component at runtime from a plain JSX external script

Time:05-08

In general terms, what are the options that I have to load and render in runtime a React component that I have in an uncompiled JSX plain script somewhere: maybe from a string or from a url. Obviously the component script can have imports from other (static) components of the same app or from other external packages.

Note: it's for an internal web app of a company, that is, there are no strong security requirements.

CodePudding user response:

The only easy-ish option I'm aware of for something like that is to use Babel Standalone, which does JSX to JS transformation on the client-side. Insert the JSX string into a <script type="text/babel">, and include React, React DOM, and Babel Standalone as scripts on the page.

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<div class='react'></div>

<script>
const jsxTextToInsert = `
    const App = () => {
        return 'foo';
    };

    ReactDOM.render(<App />, document.querySelector('.react'));
`;

const script = document.body.appendChild(document.createElement('script'));
script.type = 'text/babel';
script.textContent = jsxTextToInsert;
</script>

  • Related