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, we will use both React and ReactDOM CDN in our HTML file to run our React app instead of installing the create-react-app package.

<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> with id="root" 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>

📖 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.
What is 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>

Note:
This post is one of my TIL notes based on my learning on Scrimba platform.

Comments (2)

Rahul's photo

Cool writeup.

Ayu Adiati's photo

Thank you, Rahul 😊