jeudi 5 août 2021

Inject a React.js component to a static HTML site with from a url?

I was wondering if I could add a React.js code from an external site to a static HTML's Head just by referring to it:

<script src="https://somesite.com/code.js"></script>

And inside, use a function to add the React.js library, and the code I want that would appear on the static HTML site:

let reactScript1 = document.createElement('script');
reactScript1.src = 'https://unpkg.com/react@16/umd/react.development.js';
document.head.append(reactScript1)
let reactScript2= document.createElement('script');
reactScript2.src = 'https://unpkg.com/react-dom@16/umd/react-dom.development.js';
document.head.append(reactScript2)
let reactScript3 = document.createElement('script');
reactScript3.src = 'https://unpkg.com/babel-standalone@6.15.0/babel.min.js';
document.head.append(reactScript3)


ReactDOM.render(
  <React.StrictMode>
    <Alert/>
  </React.StrictMode>,
  document.getElementById('root')
);

function Alert () {
    const [count, setCount] = React.useState(0);
    return (
      <div>
        <p>You clicked {count} times</p>
        <button onClick={() => setCount(count + 1)}>
          Click me
        </button>
      </div>
    )
}

I'm sure it's possible, but how?

Thanks!




Aucun commentaire:

Enregistrer un commentaire