chan.dev/ lessons/ epicreact

Create a User Interface with React’s createElement API

Let’s add React to our script.

To do this, we’ll use the CDN esm.sh. This lets us import the React, right from the internet, without having to pre-install it, or bundle our code.

Our element doesn’t render yet because we’re still using the DOM to append it to the rootElement. We need React’s companion library that ReactDOM to communicate between React and the DOM.

Save, refresh, and we’ll see the text “Hello React” in the browser. Check it to make sure the className is still applied — it is.

Congrats, we are now have a React app:

<body>
<div id="root"></div>
<script type="module">
import React from 'https://esm.sh/react@18.2.0'
import ReactDOM from 'https://esm.sh/react-dom@18.2.0/client'
const rootElement = document.getElementById('root')
const element = React.createElement('div', {
children: 'Hello React',
className: 'greeting',
})
ReactDOM.createRoot(rootElement).render(element)
</script>
</body>