Here's a secret about React--it's a library for creating UIs, but not a library for rendering UIs. In itself, it has no mechanism for rendering a UI to the browser.
Fortunately, the creators of React also have a package called ReactDOM for exactly this purpose. Let's install it and then see how it works.
First, we install it with yarn add [email protected].
Then, require it in index.html in much the same way as React:
<body>
<img src="assets/icon.png" id="test-image"/>
<h1>Hello world!</h1>
<div id="root"></div>
<script src="../node_modules/react/dist/react.js"></script>
<script src="../node_modules/react-dom/dist/react-dom.js"></script>
<script>
console.log(React.createElement('h1', null, 'Hello from react!'));
</script>
</body>
ReactDOM has a function called render, which takes two arguments: the React element to be rendered to the screen (hey, we have that already!), and the HTML element it will be rendered inside.
So, we have the first argument, but not the second. We need something in our existing HTML we can grab and hook into; ReactDOM will inject our React element inside of it.
So, below our existing <h1> tag, create an empty div with the ID root.
Then, in our ReactDOM.render function, we’ll pass in the React element, and then use document.getElementById to grab our new div.
Here's what our index.html should look like:
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<link rel="stylesheet" href="assets/app.css">
<link rel="shortcut icon" href="assets/favicon.ico" type="image/x-icon">
</head>
<body>
<img src="assets/icon.png" id="test-image"/>
<h1>Hello world!</h1>
<div id="root"></div>
<script src="../node_modules/react/dist/react.js"></script>
<script src="../node_modules/react-dom/dist/react-dom.js"></script>
<script>
ReactDOM.render(React.createElement('h1', null, 'Hello from react!'),
document.getElementById('root'));
</script>
</body>
</html>
Reload the page, and you should see 'Hello from React!' text in the middle of the screen!