ReactDOM.render()

ReactDOM.render()

Subscribe to my newsletter and never miss my upcoming articles

Hello Fellow Codenewbies 👋

One functionality of ReactDOM is to render React elements to the web page, which can be achieved with ReactDOM.render() method.

Syntax

ReactDOM.render(element, container[, callback])

We can see it this way:

ReactDOM.render(WHAT to render, WHERE to render[, callback if any])

Prerequisite

Before we dive in, in this post we will use both React and ReactDOM CDN links in an HTML file to run the React app instead of installing the create-react-app. That way you can see and understand how react-dom dependency works under the hood.

<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

We also need Babel to convert the JSX syntax.

<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

ReactDOM.render() In Action

Let's create a <div> with id="root" in an index.html file.

<html>
    <head>
        ...
    </head>
    <body>
        <div id="root"></div>
        <!-- CDN Links -->
        ...
    </body>
</html>

Anything that comes between the opening and the closing div tag is where React will render what we've created.
The <div id="root"></div> is the container for our entire application.

Now we will render an h1.
Since we need Babel to translate the JSX, we will run the ReactDOM.render() in <script type="text/babel">.

<script type="text/babel">
  ReactDOM.render(<h1>Hello World</h1>, document.getElementById("root"))
</script>

📖 How to read:
Render h1 in the <div> with id="root".

As you can see, we put the HTML element of h1 in the middle of Javascript's code as a parameter. That entire line of code is called JSX.
We will talk more about JSX in the next post.

Conclusion

  • ReactDOM.render() is a React method to render a React app to the web page.
  • ReactDOM.render() takes at least 2 parameters:
    1. element (what we want to render)
    2. container (where we want to render)

I provide here the complete code.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>ReactDOM.render()</title>
  </head>
  <body>
    <div id="root"></div>

    <!-- Babel CDN Link -->
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

    <!-- React & ReactDOM CDN Links -->
    <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> 
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

    <!-- Render to page -->
    <script type="text/babel">
      ReactDOM.render(<h1>Hello World</h1>, document.getElementById("root"))
    </script>
  </body>
</html>
 
Share this