React: The Virtual DOM

 what is DOM?

Document Object Model is representation of html elements in the form tree of JavaScript object. 


For example 

{html:{head: {title:{value:'Welcome to my website'}, body:{h1:{value: 'Cat Photo App'}}} 

using Javascript we can modify it.

let h1 = document.getElementByTagName('h1'); // {value:'Cat'}

h1.value = 'Cat Lovers App' // we modified the DOM


Using JavaScript , jQuery, developers having making website this way.

 

Problems with this type of Development:

1.  slow rendering issues: every modification of element is costly

2. It's hard to keep track of changes :

 


ReactJS introduced Virtual DOM

 Virtual DOM is representation of real DOM. 

It makes us feel as we are creating a entire new Real DOM. Everytime there is any change in Virtual DOM.

 There is change in Virtual DOM (like timer update, button clicked). React uses Algorithms to update subtrees of Virtual DOM. After that new Virtual DOM is mounted on Real DOM.

Is re-creating at every change slow?

It may sound like slow. But React has all taken care for us.


Virtual DOM Pieces

React's Virtual DOM is tree of ReactElements.

 ReactElement is DOM in virtual DOM that will be placed inside real DOM.

 

Here onwards we will begin with Learning it practically.

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

   This is where are ReactElement is mounted in Real DOM

<script>
var boldElement = React.createElement('b');
</script>

We will create react Element using React.createElement()

Let's render this on browser

For this we will use

 ReactDOM.render('ReactElement or root of ReactElements', 'Place in DOM')

 
var mountElement = document.getElementById('root')
ReactDOM.render(boldElement, mountElement)

 Open html file in Browser. There is nothing on screen but empty reactElement is mounted into real DOM

Adding Text (with Children)

Our text will child of boldElement 

our React.createElement() takes three agruments

1. The DOM element type

2. props (for element or pass it further to children)

3. Child Element

 

Note: for now i am setting props to null as we are not going into too much details.

 Children of Element should be

1. ReactElement

2. String or number

3. An Array of ReactNodes

 

var boldElement = React.createElement('b', null, 'Mr Beast is best');

 Reload the page

 

ReactDOM.react()

mounted our reactElement in the real DOM 


Benefits of Virtual DOM

 We can have different types of Virtual DOM for Different situations 

like React Native for native mobile view, other frameworks etc.

(we be covered in future in future articles.)



Link to Code

 

 

Comments

Popular posts from this blog

My Education