Inception

<script>
  const root = document.getElementById("root");
  const h1 = document.createElement("h1");
  h1.textContent = "Namaste React";
  root.appendChild(h1);
</script>

It's Time to add React to our code

But we aren't going to do npm create react app yet. Wait!

Key Points:

To learn more about using React with a CDN, you can refer to the official React CDN documentation.

Now add both the CDN links to the index.html file in the <script> tags at the end of the <body> tag to add React to your project.

<body>
  <div id="root"></div>
  <script
    crossorigin
    src="[https://unpkg.com/react@18/umd/react.development.js](https://unpkg.com/react@18/umd/react.development.js)"
  ></script>
  <script
    crossorigin
    src="[https://unpkg.com/react-dom@18/umd/react-dom.development.js](https://unpkg.com/react-dom@18/umd/react-dom.development.js)"
  ></script>
</body>

As soon as we add these CDN links, we'll gain the superpower of React and ReactDOM.

We can check this by opening the browser console and typing React and ReactDOM. Below is what we should see:

React and ReactDOM in Console

Now we will write React code to render Namaste React on our webpage.

Add the following script to your index.html file within the <script> tags, placed at the end of the <body> tag:

<script>
  const heading = React.createElement("h1", {}, "Namaste React!!");
  const root = ReactDOM.createRoot(document.querySelector("#root"));
  root.render(heading);
</script>

Well, React is very intuitive to understand, but for reference, here is the explanation for each line of code:

  1. Creating a React Element

const heading = React.createElement("h1", {}, "Namaste React!!");

  1. Selecting the Root Element

const root = ReactDOM.createRoot(document.querySelector("#root"));

  1. Rendering the Element

root.render(heading);

Key Points:

Interesting Question from Akshay Saini

What will happen if we add lots of other elements inside the root element where React is rendering?

Consider the following HTML:

<body>
  <div id="root">
    <h1 id="title">Hello World</h1>
    <h1 id="title">Hello World</h1>
    <h1 id="title">Hello World</h1>
  </div>
</body>

In this case, what will happen to the heading rendered by React? Will it appear before or after all the existing tags?

Developer Community Practice

In the developer community, it is common to place the text Not Rendered inside the root element to help identify issues with React rendering.

Consider the following HTML:

<body>
  <div id="root">Not Rendered</div>
</body>

So JSX was built

Here's a brief comparison of using React.createElement() versus JSX:

Using React.createElement():

const element = React.createElement('h1', null, 'Hello, world!');

Using JSX:

const element = <h1>Hello, world!</h1>;

Thanks to JSX for making our lives easier.