Before we dive deeper into this topic, let me familiarize you with a few terms:
- HTML – HTML is a standard markup language for creating web pages with various DOMs.
Now let’s start our short coding journey from HTML to React….
Below is an HTML code snippet:
The output is a blank screen as we do not have any HTML element within the body.
The code below has 1 heading tag inside <div> printing Hello from HTML.
And the output will be as follows;
And the output is as follows:
The document here refers to our HTML page, and createElement is used to create HTML tags. I passed the HTML tag “h1” as a parameter inside createElement.
So document.createElement creates HTML tags. And we stored it in a variable called heading.
document.getElementById(“root”) gives us the reference of an HTML tag/element having id = “root.” In our case, <div is the HTML tag with id = “root,” and we store this reference in a variable called root.
Now we are adding the <h1> tag stored in the heading inside into our <div> stored inside the root, using root.appendChild(heading) by passing heading as a parameter.
root.appendChild adds the heading tag as a child inside the div tag. So appendChild() function adds the html tag as a child inside any parent HTML tag.
Now we will try to render the same heading tag using React. See the code below:
The output will be as below:
Now, let us understand the above code line by line.
We need to import two React libraries from the CDN to write the React code. Here CDN means Content Delivery Network. And the two libraries are React and React-dom.
What are react.development.js and react-dom.development.js?
It means we are importing the React and React-dom libraries for our development environment. If we use both libraries in the production environment, it should be react.production.min.js and react-dom.production.min.js. Here production.min.js signifies that we are using the libraries for the production environment in the minified version.
Why do we use crossorigin?
As per W3School, The crossorigin attribute sets the mode of the request to an HTTP CORS Request. Web pages often make requests to load resources on other servers. Here is where CORS comes in. A cross-origin request requests a resource (e.g., style sheets, iframes, images, fonts, or scripts) from another domain.
Let’s move ahead now.
Here React.createElement() is used to create a React element. It requires three parameters:
- Attributes, in React, we call props
- Content or child element to be placed inside the TagName
What is a React Element?
ReactDOM.createRoot() is used to create a root element in React inside which we can render other React elements.
Root. Render () renders the React element inside the root element/DOM.
Stay tuned for more blogs on React.
View our LinkedIn, here.