Rendering React Elements in the DOM

As seen briefly in the JSX elements post, rendering React elements in the DOM can be achieved using the render() function of the ReactDOM global.

The function takes two parameters: an element, which can contain multiple nested children elements, and a node, which is usually the root DOM node used to render the content within.

const element = ( 
    <p>I am an element</p>
);

ReactDOM.render(
    element,
    document.getElementById('root')
);

The above example assumes that a DOM element with the id of root exists, so this element needs to exist somewhere in your HTML file.

The JSX needs to be compiled into JavaScript, and this is be achieved by using a library such as Babel.

For non-Node.js environments, you could include the Babel library into your site’s <head>, along with the React libraries. An example HTML document with working React code might look like the below.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>React Testing</title>
    <script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/[email protected]/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">

    const element = (
        <p>I am an element</p>
    );

    ReactDOM.render(
        element,
        document.getElementById('root')
    );

    </script>
  </body>
</html>

Note that the React code resides within a pair of <script type="text/babel"> nodes. It should be noted that these nodes should not be used when your application runs in production mode as code transformation is slow.

If you’ve installed React via a node environment, such as create-react-app in the React Components post, then you’ll notice the following code in the src/index.js file.

ReactDOM.render(<App />, document.getElementById('root'));

It’s important to note here that <App /> starts with a capital letter. This specifically tells React to look for a component rather than a regular DOM element.

If instead the code was modified so that a lowercase definition was used.

ReactDOM.render(<app />, document.getElementById('root'));

React would consider <app /> to be a DOM element, and <app></app> would display in the browser, rather than the content returned within the App component.

When ReactDOM.render() occurs in the above example, the following steps take place.

1. React calls the App component.

2. The App component returns the JSX content defined in the src/App.js file as the result.

3. The React DOM efficiently updates the DOM to match the content returned.

One of the key benefits of using React is that it only updates DOM elements if they differ from the previous state. You can read more about it and view an example in the React documentation.