What is an element?
An element is a smallest unit on a web page. Whatever you see on a web page is an element. Examples of elements are text box, checkbox, radio button, headings, span etc. A user always interacts with elements.
An element in react is not a normal HTML element but it is an object. This will be demonstrated later in this section.
In order to render elements on a web page in react, you need to follow below two steps:
1. Create an element using JFX syntax.
2. Display it using render method of
ReactDOM class from
render method takes 2 arguments.
First one is the JFX element we created in step 1 and second is the reference to another element inside which the newly created element will be rendered. In other words, a reference to the parent element of the new element.
The project which we created in the previous section would be having an index.html and an index.js file highlighted in the image below.
Suppose we need to display a heading with text “Hello World!”. We can do this using above two steps as
import React from 'react'; import ReactDOM from 'react-dom'; // create element const element = <h1>Hello World!</h1> // render it on page ReactDOM.render(element, document.getElementById('root'));
Copy the above code and write it in the index.js file in the newly created application. Note that the parent element in the
render method is an element having
id as root. This element is present in the index.html file.
Once you save index.js file and move ahead to the browser, you will see the heading with label Hello World!.
Now go to developer tools(press F12 on browser window) and inspect this element, you will see a structure as
which shows that the new element is placed inside the root element.
React elements are objects
As stated earlier, elements created using JSX are objects. Thus, the h1 tag which we created above was also an object.
For demonstrating it, just place the following code in the index.js file where we are creating an element and logging it to the browser console.
// create element const element = <h1>Hello World!</h1> // log it on console console.log(element);
Now move to the browser and see the output in developer tools. You will see something like
which shows our h1 tag as an object.