0

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.

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

It works well. Although I haven't been able to get it to work when inserting an 'import' of another component. This one already existing in the app. I'll keep trying.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.