Adding react to a legacy website

To work with react on a legacy website, we can add it via CDN.

<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

Besides, react and react-dom, we need the babel for JSX support and the latest JS features.

Finally, add your components/scripts.

<script type="text/babel" data-plugins="transform-modules-umd" data-presets="react" data-type="module" src="/js/components/hello-world.js"></script>
<script type="text/babel" data-plugins="transform-odules-umd" data-presets="react" data-type="module" src="/js/components/app.js"></script>

hello-world.js

const HelloWorld = () => {
    return <h1>Hello World</h1>;
};
export default HelloWorld;

app.js

import HelloWorld from "./hello-world";

const App = () => {
    return <HelloWorld/>;
};

const e = React.createElement;
const domContainer = document.querySelector("#app");
const root = ReactDOM.createRoot(domContainer);
root.render(e(Test));

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>React CDN Demo</title>
    <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  </head>
  <body>
    <div id="app"></div>
    <script type="text/babel" data-plugins="transform-modules-umd" data-presets="react" data-type="module" src="/js/components/hello-world.js"></script>
    <script type="text/babel" data-plugins="transform-odules-umd" data-presets="react" data-type="module" src="/js/components/app.js"></script>
  </body>
</html>
Published
Categorized as React