React

How to render elements in React

render

Elements are building blocks for any React application.

const element = <h1>Hello, Reader</h1>;

So what is the difference between browser dom elements and React Elements. Browser dom elements are expensive to create but React Elements are simple objects and they are very cheap to create.

Also some react beginners confuse between elements and components in React. Elements are building blocks of components.

How to render an element to an html dom?

First thing is you need to create a div in your html file.

<div id="root"></div>

It is general practice to call to a root dom node. If you are writing an application from scratch, then this will be typically the only html code in your html file and all react manipulation will happen here.

Now to render an element inside a dom node, you need to use ReactDOM render method. Below is a simple example.

const element = <h1>Hello, Reader</h1>;
ReactDOM.render(element, document.getElementById('root'));

Are React Elements Mutable?

React elements are not mutable. React elements are like a snapshot, picture taken at a point in time.

In below example I have created a stop watch, here we are creating and rendering a new element every second.

const initDate = new Date();
function tick() {
  const dateNow = new Date();
  var diff = Math.abs(dateNow - initDate);
  var intdiff = Math.round(diff/1000);
  const element = (
    <div>
      <h1>Hello from Ojb Labs!</h1>
      <h2>It is {intdiff} seconds since you opened this screen.</h2>
    </div>
  );
  // highlight-next-line
  ReactDOM.render(element, document.getElementById('root'));
}

setInterval(tick, 1000);

Below is a live working example for the same.

https://codepen.io/anilpank/pen/LYPXgev

In our view React developers did one thing really good was to make React elements immutable and props (can never be changed). We will talk about props in our next post. But this particular feature is what makes React so bug free to write to. People coming from a Java background could also agree how it is recommended to do immutable classses to make them thread safe and easily shareable across multiple threads.

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

About anil

Hi, I'm Anil Verma. I have a passion for teaching and developing awesome front end apps. I was involved in development of post processor for Nastran(built by NASA). More recently I have been building supply chain apps at E2open.
View all posts by anil →

Leave a Reply

Your email address will not be published. Required fields are marked *