<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by deathmood on Medium]]></title>
        <description><![CDATA[Stories by deathmood on Medium]]></description>
        <link>https://medium.com/@deathmood?source=rss-8df1c41d56f1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GHAdR82a2YqtegoRlG-nIA.png</url>
            <title>Stories by deathmood on Medium</title>
            <link>https://medium.com/@deathmood?source=rss-8df1c41d56f1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 10:43:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deathmood/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Write your Virtual DOM 2: Props & Events]]></title>
            <link>https://medium.com/@deathmood/write-your-virtual-dom-2-props-events-a957608f5c76?source=rss-8df1c41d56f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a957608f5c76</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[deathmood]]></dc:creator>
            <pubDate>Mon, 06 Jun 2016 19:09:08 GMT</pubDate>
            <atom:updated>2016-06-11T10:34:41.421Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JJfVEMOHoIG_YJO8zSyalQ.jpeg" /></figure><p>Hi there!</p><p>I’m so happy to continue this topic and to share with you all the next things that eventually will allow us to move from the ‘baby’ Virtual DOM implementation to smth we can use in real projects.</p><p>Today we’ll talk mainly about setting/diffing attributes (props) and handling events. Ok, let’s go ;)</p><blockquote>It is the second article in series. If you’re new here be sure to read <a href="https://medium.com/@deathmood/how-to-write-your-own-virtual-dom-ee74acc13060">introduction</a>.</blockquote><h3>Dealing with Babel</h3><p>Before starting with props we need to fix one small gap in our previous implementation. When we have just node without attributes (props) like this:</p><pre>&lt;div&gt;&lt;/div&gt;</pre><p>Babel, when transpiling this will set <strong><em>props</em></strong> property of element to ‘null’, because there is no attributes. Thus we’ll have:</p><pre>{ type: ‘’, props: null, children: [] }</pre><p>It is better to set it to <strong><em>empty object</em></strong> by default — then we’ll not have errors while iterating properties (you’ll see it later). In order to fix that, we will modify our <strong><em>h(…)</em></strong> function like this:</p><pre>function h(type, props, …children) {<br>  return { type, props: props || {}, children };<br>}</pre><h3>Setting props</h3><p>Setting props is really simple — you’ll see. Remember our DOM representation? There we store props like plain JS object, so for this markup:</p><pre>&lt;ul className=”list” style=”list-style: none;”&gt;&lt;/ul&gt;</pre><p>We’ll have such in-memory representation:</p><pre>{ <br>  type: ‘ul’, <br>  props: { className: ‘list’, style: ’list-style: none;’ } <br>  children: []<br>}</pre><p>Thus each field in <strong><em>props </em></strong>object is <strong><em>attribute name</em></strong>, and value of this field is <strong><em>attribute value</em></strong>. So we only need to set this things on real DOM node. Let’s write a function-wrapper around <strong><em>setAttribute(…)</em></strong> method:</p><pre>function setProp($target, name, value) {<br>  $target.setAttribute(name, value);<br>}</pre><p>Well now that we know how to set one attribute (prop) — we can set them all, just iterating through all fields of <strong><em>props</em></strong> object:</p><pre>function setProps($target, props) {<br>  Object.keys(props).forEach(name =&gt; {<br>    setProp($target, name, props[name]);<br>  });<br>}</pre><p>Now remember <strong><em>createElement(…)</em></strong> function? We’ll just <strong><em>setProps(..) </em></strong>there immediately after real DOM node creation:</p><pre>function createElement(node) {<br>  if (typeof node === ‘string’) {<br>    return document.createTextNode(node);<br>  }<br>  const $el = document.createElement(node.type);<br>  setProps($el, node.props);<br>  node.children<br>    .map(createElement)<br>    .forEach($el.appendChild.bind($el));<br>  return $el;<br>}</pre><p>But this is not the end. We’ve forgotten some small things. First, ‘class’ is reserved word in JS so we’ll not use it as property name. We’ll use ‘className’:</p><pre>&lt;nav className=”navbar light”&gt;<br>  &lt;ul&gt;&lt;/ul&gt;<br>&lt;/nav&gt;</pre><p>But there is no ‘className’ attribute in real DOM, so we should handle this in our <strong><em>setProp(…)</em></strong> function.</p><p>Another thing is that I found it to be more convenient to set boolean DOM attributes (e.g. checked, disabled) with boolean value like here:</p><pre>&lt;input type=”checkbox” checked={false} /&gt;</pre><p>In this sample I expect that ‘checked’ attribute won’t be set on real DOM element. But in reality it will, ’cause as you know existence of this property is enough for it to be set. So we need to fix that. Notice that we’re not only setting attribute, but also setting corresponding boolean property on element reference:</p><pre>function setBooleanProp($target, name, value) {<br>  if (value) {<br>    $target.setAttribute(name, value);<br>    $target[name] = true;<br>  } else {<br>    $target[name] = false;<br>  }<br>}</pre><p>Ok. And the last thing to say here is custom properties. I mean, that it is our own implementation, so in future we might want to have properties that have different role and should not be displayed in DOM. So we’ll write a function to check if this property is custom or not. For now it will be empty, ’cause we do not have any custom properties yet:</p><pre>function isCustomProp(name) {<br>  return false;<br>}</pre><p>And here is our completed <strong><em>setProp(..)</em></strong> function that fixes all the problems above:</p><pre>function setProp($target, name, value) {<br>  if (isCustomProp(name)) {<br>    return;<br>  } else if (name === ‘className’) {<br>    $target.setAttribute(‘class’, value);<br>  } else if (typeof value === ‘boolean’) {<br>    setBooleanProp($target, name, value);<br>  } else {<br>    $target.setAttribute(name, value);<br>  }<br>}</pre><p>Now let’s test that in JSFiddle:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2Fdeathmood%2Fst5cyz16%2Fembedded%2F&amp;url=https%3A%2F%2Fjsfiddle.net%2Fdeathmood%2Fst5cyz16%2F&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F99633d9077a97545dcc1a21b5688db97%2F%3Fdefault%3D%26s%3D80&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/f95bb0134e84251c9645aaec09d3da11/href">https://medium.com/media/f95bb0134e84251c9645aaec09d3da11/href</a></iframe><h3>Diffing props</h3><p>Ok, now that we can create elements with props, it’s time to think of how to diff them. Well, eventually it comes to either <strong><em>setting</em></strong> property or <strong><em>removing</em></strong> it. We have already written functions that are able to <strong><em>set props</em></strong>, now let’s write functions that can <strong><em>remove</em></strong> them. Actually it is very straightforward process and I won’t even comment it:</p><pre>function removeBooleanProp($target, name) {<br>  $target.removeAttribute(name);<br>  $target[name] = false;<br>}</pre><pre>function removeProp($target, name, value) {<br>  if (isCustomProp(name)) {<br>    return;<br>  } else if (name === ‘className’) {<br>    $target.removeAttribute(‘class’);<br>  } else if (typeof value === ‘boolean’) {<br>    removeBooleanProp($target, name);<br>  } else {<br>    $target.removeAttribute(name);<br>  }<br>}</pre><p>Now let’s write a function <strong><em>updateProp </em></strong>that will compare two properties — old and new and modify real DOM node according to result of that comparation. Actually we have to handle next cases:</p><ul><li>There is no property with such name on a <strong><em>new node</em></strong> — thus we need to remove it</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*N18Z791AZ-0c59IW1JNl3Q.png" /></figure><ul><li>There is no property with such name on <strong><em>old node</em></strong> — thus we need to set it</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*TWNB5FSzfjqGa0g_D8OXtg.png" /></figure><ul><li>Property with such name exists both on a <strong><em>new</em></strong> and <strong><em>old</em></strong> nodes — then we need to compare their <strong><em>values </em></strong>— if they are not equal we need to set that property again with value of the <strong><em>new node</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*W0jGFee-2ptAP1Lm05nzDg.png" /></figure><ul><li>In other cases property hasn’t changed and we do not need to do anything</li></ul><p>Ok. Here is the function that does exactly the same to one prop:</p><pre>function updateProp($target, name, newVal, oldVal) {<br>  if (!newVal) {<br>    removeProp($target, name, oldVal);<br>  } else if (!oldVal || newVal !== oldVal) {<br>    setProp($target, name, newVal);<br>  }<br>}</pre><p>Isn’t that was simple? But node can have more than one property — so let’s write a function that will be able to iterate through all props and call <strong><em>updateProp(…)</em></strong> function for each pair:</p><pre>function updateProps($target, newProps, oldProps = {}) {<br>  const props = Object.assign({}, newProps, oldProps);<br>  Object.keys(props).forEach(name =&gt; {<br>    updateProp($target, name, newProps[name], oldProps[name]);<br>  });<br>}</pre><p>Notice here we are creating compound object, that contains both props of new and old node. Thus, while iterating through props we might have some `undefined`s but that is ok — our function can handle it.</p><p>The last thing is to put that function in our <strong><em>updateElement(…)</em></strong> function (remember it from our previous journey?). Where should we put it? Well probably if node hasn’t changed and we are going to diff its children we might want to check its properties before. So we put that in the last `if` clause right before diffing child nodes:</p><pre>function updateElement($parent, newNode, oldNode, index = 0) {<br>  ...</pre><pre>  } else if (newNode.type) {<br>    updateProps(<br>      $parent.childNodes[index],<br>      newNode.props,<br>      oldNode.props<br>    );<br> <br>    ...<br>  }<br>}</pre><p>And this is it. Go forward and test it:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2Fdeathmood%2Furhpk7os%2Fembedded%2F&amp;url=https%3A%2F%2Fjsfiddle.net%2Fdeathmood%2Furhpk7os%2F&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F99633d9077a97545dcc1a21b5688db97%2F%3Fdefault%3D%26s%3D80&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/61be6c3ccddf69ec67e574a9aa0923d7/href">https://medium.com/media/61be6c3ccddf69ec67e574a9aa0923d7/href</a></iframe><h3>Events</h3><p>Of course to have a normal dynamic app we need to know how handle events. Well at this point we could already <strong><em>querySelector(…)</em></strong> our nodes by e. g. class and then <strong><em>addEventListener(…)</em></strong> to them. But it is not interesting. Actually I would like to have smth like in React:</p><pre>&lt;button onClick={() =&gt; alert(‘hi!’)}&gt;&lt;/button&gt;</pre><p>Yeah, this looks cool. Well, as you see we are using <strong><em>props</em> </strong>here to declare an event listener. And our property name starts with `on` prefix:</p><pre>function isEventProp(name) {<br>  return /^on/.test(name);<br>}</pre><p>To extract <strong><em>event name</em></strong> from the <strong><em>prop name</em></strong> we’ll write next function (it just removes `on` prefix):</p><pre>function extractEventName(name) {<br>  return name.slice(2).toLowerCase();<br>}</pre><p>It seems, that if we are declaring our events in <strong><em>props</em></strong> object, then we should handle them in our <strong><em>setProps(..)/updateProps(…) </em></strong>functions. But think again about it. How can you really <strong><em>diff functions</em></strong>? How?</p><p>You can’t compare them with equal signs. Well, you can use <strong><em>toString()</em></strong> method and compare code of the functions. But here we’ve go some problems. There are some functions with native code inside so we can’t diff them in such way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*kHULR4jucUYsJmRoS5aSBA.png" /></figure><p>Of course we could handle that with event bubbling — we could write our own event manager that will be attached to `body`or to root element and will handle all events of inner elements. Thus we could re-add event listeners on each update and that will not be so expensive.</p><p>But will not try to do that here. It adds more problems and in reality our event listeners are not changing so often. So let’s set our event listeners only <strong><em>once </em></strong>at<strong><em> </em></strong>element creation.</p><p>So we do not want our <strong><em>setProps(…)</em></strong> function to set this events props on real DOM node. We want to handle adding event listeners ourselves. Ho to do this? Remember our function for checking for custom props? Now it won’t be empty:</p><pre>function isCustomProp(name) {<br>  return isEventProp(name);<br>}</pre><p>Adding event listeners when we know a real DOM node and have <strong><em>props </em></strong>object is also very straightforward:</p><pre>function addEventListeners($target, props) {<br>  Object.keys(props).forEach(name =&gt; {<br>    if (isEventProp(name)) {<br>      $target.addEventListener(<br>        extractEventName(name),<br>        props[name]<br>      );<br>    }<br>  });<br>}</pre><p>Let’s put that in our <strong><em>createElement</em></strong> function:</p><pre>function createElement(node) {<br>  if (typeof node === ‘string’) {<br>    return document.createTextNode(node);<br>  }<br>  const $el = document.createElement(node.type);<br>  setProps($el, node.props);<br>  addEventListeners($el, node.props);<br>  node.children<br>    .map(createElement)<br>    .forEach($el.appendChild.bind($el));<br>  return $el;<br>}</pre><h3>Re-adding events</h3><p>What if you really need to re-add event listener? Let’s keep it simple. There is one very simple solution. But unfortunately it harms performance. We will introduce one more custom property called `forceUpdate`. Remeber, how we check if node changed? We will modify this function:</p><pre>function changed(node1, node2) {<br>  return typeof node1 !== typeof node2 ||<br>         typeof node1 === ‘string’ &amp;&amp; node1 !== node2 ||<br>         node1.type !== node2.type ||<br>         node.props.forceUpdate;<br>}</pre><p>So if `forceUpdate` is true the node will be entirely recreated and thus new event listeners will be added. We should handle it also here, ’cause we do not want this prop to be set on a real DOM node:</p><pre>function isCustomProp(name) {<br>  return isEventProp(name) || name === ‘forceUpdate’;<br>}</pre><p>And that’s pretty much all. Yeah, this solution is bad for performance. But it is simple :))</p><p>Go ahead and test it:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2Fdeathmood%2Fx09sL59r%2Fembedded%2F&amp;url=https%3A%2F%2Fjsfiddle.net%2Fdeathmood%2Fx09sL59r%2F&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F99633d9077a97545dcc1a21b5688db97%2F%3Fdefault%3D%26s%3D80&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1a38dd8085cac3fbe977f69b2f083e2/href">https://medium.com/media/f1a38dd8085cac3fbe977f69b2f083e2/href</a></iframe><h3>Conclusion</h3><p>And that’s it :)) Hope that it was interesting for you. If you know a simple way to diff event listeners it would be great if you share your ideas in comments.</p><p>In the next article we are going to write a custom component system for our Virtual DOM :))</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a957608f5c76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to write your own Virtual DOM]]></title>
            <link>https://medium.com/@deathmood/how-to-write-your-own-virtual-dom-ee74acc13060?source=rss-8df1c41d56f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee74acc13060</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[deathmood]]></dc:creator>
            <pubDate>Wed, 01 Jun 2016 14:11:05 GMT</pubDate>
            <atom:updated>2016-06-11T10:35:22.382Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U1wSnKCYJ-XDsST-HQS1bQ.jpeg" /></figure><p>There are two things you need to know to build your own Virtual DOM. You do not even need to dive into React’s source. Or into source code of any other Virtual DOM implementations. They are so large and complex — but in reality the main part of Virtual DOM can be written in less than ~50 lines of code. 50. Lines. Of. Code. !!!</p><p>Here are these two concepts:</p><ul><li>Virtual DOM is any kind of representation of a real DOM</li><li>When we change something in our Virtual DOM Tree, we get a new Virtual Tree. Algorithm compares these two trees (old and new), finds differences and makes only necessary small changes to real DOM so it reflects virtual</li></ul><p>That’s all! Let’s dive deeper into each of these concepts.</p><blockquote>UPDATE: The second article about setting props &amp; events in Virtual DOM is <a href="https://medium.com/@deathmood/write-your-virtual-dom-2-props-events-a957608f5c76">here</a></blockquote><h3>Representing our DOM Tree</h3><p>Well, first we need to store somehow our DOM tree in memory. And we can do that with plain old JS objects. Suppose we have this tree:</p><pre>&lt;ul class=”list”&gt;<br>  &lt;li&gt;item 1&lt;/li&gt;<br>  &lt;li&gt;item 2&lt;/li&gt;<br>&lt;/ul&gt;</pre><p>Looks pretty simple, yeah? How could we represent that with just JS objects?</p><pre>{ type: ‘ul’, props: { ‘class’: ‘list’ }, children: [<br>  { type: ‘li’, props: {}, children: [‘item 1’] },<br>  { type: ‘li’, props: {}, children: [‘item 2’] }<br>] }</pre><p>Here you can notice two things:</p><ul><li>We represent DOM elements with objects like</li></ul><pre>{ type: ‘…’, props: { … }, children: [ … ] }</pre><ul><li>We represent DOM text nodes with plain JS strings</li></ul><p>But writing big trees in such way is quite difficult. So let’s write a helper function, so it will be easier for us to understand structure:</p><pre>function h(type, props, …children) {<br>  return { type, props, children };<br>}</pre><p>Now we can write our DOM tree like this:</p><pre>h(‘ul’, { ‘class’: ‘list’ },<br>  h(‘li’, {}, ‘item 1’),<br>  h(‘li’, {}, ‘item 2’),<br>);</pre><p>It looks a lot cleaner, yeah? But we can go even further. You’ve heard about JSX, haven’t you? Yes, I want it here too. So how does it work?</p><p>If you read official Babel JSX documentation <a href="https://babeljs.io/docs/plugins/transform-react-jsx/">here </a>, you’ll know, that Babel transpiles this code:</p><pre>&lt;ul className=”list”&gt;<br>  &lt;li&gt;item 1&lt;/li&gt;<br>  &lt;li&gt;item 2&lt;/li&gt;<br>&lt;/ul&gt;</pre><p>Into smth like this:</p><pre>React.createElement(‘ul’, { className: ‘list’ },<br>  React.createElement(‘li’, {}, ‘item 1’),<br>  React.createElement(‘li’, {}, ‘item 2’),<br>);</pre><p>Notice any similarities? Yes, yes.. If we could just replace those <strong><em>React.createElement(…)’</em></strong>s with our <strong><em>h(…)’</em></strong>s calls… It turns out we can — by using smth called<em> </em><strong><em>jsx pragma</em></strong>. We just need to include comment-like line at the top of our source file:</p><pre>/** @jsx h */</pre><pre>&lt;ul className=”list”&gt;<br>  &lt;li&gt;item 1&lt;/li&gt;<br>  &lt;li&gt;item 2&lt;/li&gt;<br>&lt;/ul&gt;</pre><p>Well, it actually tells Babel ‘hey, transpile that jsx but instead of <strong><em>React.createElement</em></strong>, put <strong><em>h</em></strong>’. You can put anything instead of `h` there. And that will be transpiled.</p><p>So, to sum up what I’ve said before, we will write our DOM in such way:</p><pre>/** <a href="http://twitter.com/jsx">@jsx</a> h */</pre><pre>const a = (<br>  &lt;ul className=”list”&gt;<br>    &lt;li&gt;item 1&lt;/li&gt;<br>    &lt;li&gt;item 2&lt;/li&gt;<br>  &lt;/ul&gt;<br>);</pre><p>And that will be transpiled by Babel to this code:</p><pre>const a = (<br>  h(‘ul’, { className: ‘list’ },<br>    h(‘li’, {}, ‘item 1’),<br>    h(‘li’, {}, ‘item 2’),<br>  );<br>);</pre><p>When function `h` executes, it will return plain JS objects — our Virtual DOM representation:</p><pre>const a = (<br>  { type: ‘ul’, props: { className: ‘list’ }, children: [<br>    { type: ‘li’, props: {}, children: [‘item 1’] },<br>    { type: ‘li’, props: {}, children: [‘item 2’] }<br>  ] }<br>);</pre><p>Go ahead and try that in JSFiddle (don’t forget to set Babel as your language):</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fjsfiddle.net%2Fdeathmood%2F5qyLubt4%2Fembed%2F&amp;src=https%3A%2F%2Fjsfiddle.net%2Fdeathmood%2F5qyLubt4%2Fembedded%2F&amp;type=text%2Fhtml&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b81e2a94e00281c992bf23de0756f039/href">https://medium.com/media/b81e2a94e00281c992bf23de0756f039/href</a></iframe><h3>Applying our DOM Representation</h3><p>Ok, now we have our DOM tree represented as plain JS objects, with our own structure. That’s cool, but we need to somehow create a real DOM from it. ’Cause we can’t just append our representation into DOM.</p><p>First let’s make some assumptions and set up terminology:</p><ul><li>I will write all variables with real DOM nodes (elements, text nodes) starting with `$` — so <strong><em>$parent </em></strong>will be real DOM element</li><li>Virtual DOM representation will be in variable named <strong><em>node</em></strong></li><li>Like in React, you can have only <strong><em>one root node </em></strong>— all other nodes will be inside</li></ul><p>Ok, having that said, let us write a function <strong><em>createElement(…) </em></strong>that will take a virtual DOM node and return a real DOM node. Forget about `props` and `children` for now — we’ll set up that later:</p><pre>function createElement(node) {<br>  if (typeof node === ‘string’) {<br>    return document.createTextNode(node);<br>  }<br>  return document.createElement(node.type);<br>}</pre><p>So, because we can have both<strong><em> text nodes </em></strong>— that are plain JS strings and <strong><em>elements</em></strong> — that are JS objects of type like:</p><pre>{ type: ‘…’, props: { … }, children: [ … ] }</pre><p>Thus, we can pass here both virtual text nodes and virtual element nodes — and that will work.</p><p>Now let’s think about children — each of them is also either a text node or an element. So they can also be created with our <strong><em>createElement(…) </em></strong>function. Yeah, do you feel that? It feels recursively :)) So we can call <strong><em>createElement(…) </em></strong>for each of element’s children and then <strong><em>appendChild() </em></strong>them into our element like this:</p><pre>function createElement(node) {<br>  if (typeof node === ‘string’) {<br>    return document.createTextNode(node);<br>  }<br>  const $el = document.createElement(node.type);<br>  node.children<br>    .map(createElement)<br>    .forEach($el.appendChild.bind($el));<br>  return $el;<br>}</pre><p>Wow, that looks nice. Let’s put aside node <strong><em>props </em></strong>for now. We’ll talk about them later. We do not need them for understanding basic concepts of Virtual DOM but they’ll add more complexity.</p><p>Now go ahead and try that in JSFiddle:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fjsfiddle.net%2Fdeathmood%2FcL0Lc7au%2Fembed%2Fjs%2Cresult%2F&amp;src=https%3A%2F%2Fjsfiddle.net%2Fdeathmood%2FcL0Lc7au%2Fembedded%2F&amp;type=text%2Fhtml&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b8072f7a2ad74723851d0023af95004/href">https://medium.com/media/1b8072f7a2ad74723851d0023af95004/href</a></iframe><h3>Handling changes</h3><p>Ok, now that we can turn our virtual DOM into a real DOM, it’s time to think about diffing our virtual trees. So basically we need to write an algo, that will compare two virtual trees — old and new — and make only necessary changes into real DOM.</p><p>How to diff trees? Well, we need to handle next cases:</p><ul><li>There is no old node at some place — so node was added and we need to <strong><em>appendChild(…)</em></strong> that</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*GFUWrX6pBgiDQ5Z-IvzjUw.png" /></figure><ul><li>There is no new node at some place — thus node was deleted and we need to <strong><em>removeChild(…)</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*VRoYwAeWPF0jbiWXsKb2HA.png" /></figure><ul><li>There is a different node at that place — thus node changed and we need to <strong><em>replaceChild(…)</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*6iQYEH0APjbuPvYmnD7Qlw.png" /></figure><ul><li>Nodes are the same — so we need to go deeper and diff child nodes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*x1Eq-uuqgL0z9d9qn_opww.png" /></figure><p>Ok, let us write a function called <strong><em>updateElement(…)</em></strong> that takes three parameters — <strong><em>$parent</em></strong>, <strong><em>newNode</em></strong> and <strong><em>oldNode, </em></strong>where <strong><em>$parent</em></strong> is a real DOM element-parent of our virtual node. Now we’ll see how to handle all cases that described above.</p><h3>There is no old node</h3><p>Well, it is pretty straightforward here, I won’t even comment:</p><pre>function updateElement($parent, newNode, oldNode) {<br>  if (!oldNode) {<br>    $parent.appendChild(<br>      createElement(newNode)<br>    );<br>  }<br>}</pre><h3>There is no new node</h3><p>Here we’ve got a problem — if there is no node at current place in new virtual tree — we should remove it from a real DOM — but how should we do that? Yeah, we know parent element (it is passed to function) and thus we are supposed to call <strong><em>$parent.removeChild(…) </em></strong>and pass real DOM element reference there. But we do not have that. Well, if we knew position of our node in parent, we could get its reference with <strong><em>$parent.childNodes[index], </em></strong>where<strong><em> index </em></strong>is position of our node in parent element.</p><p>Ok let’s suppose that this <strong><em>index</em></strong> will be passed to our function (and it really will be passed — you’ll see it later). So our code will be:</p><pre>function updateElement($parent, newNode, oldNode, index = 0) {<br>  if (!oldNode) {<br>    $parent.appendChild(<br>      createElement(newNode)<br>    );<br>  } else if (!newNode) {<br>    $parent.removeChild(<br>      $parent.childNodes[index]<br>    );<br>  }<br>}</pre><h3>Node changed</h3><p>First we need to write a function that will compare two nodes (old and new) and tell us if node really changed. We should consider that it can be both elements and text nodes:</p><pre>function changed(node1, node2) {<br>  return typeof node1 !== typeof node2 ||<br>         typeof node1 === ‘string’ &amp;&amp; node1 !== node2 ||<br>         node1.type !== node2.type<br>}</pre><p>And now, having <strong><em>index</em></strong> of current node in parent we can easily replace it with newly created node:</p><pre>function updateElement($parent, newNode, oldNode, index = 0) {<br>  if (!oldNode) {<br>    $parent.appendChild(<br>      createElement(newNode)<br>    );<br>  } else if (!newNode) {<br>    $parent.removeChild(<br>      $parent.childNodes[index]<br>    );<br>  } else if (changed(newNode, oldNode)) {<br>    $parent.replaceChild(<br>      createElement(newNode),<br>      $parent.childNodes[index]<br>    );<br>  }<br>}</pre><h3>Diff children</h3><p>And last, but not least — we should go through every child of both nodes and compare them — actually call <strong><em>updateElement(…)</em></strong> for each of them. Yeah, recursion again.</p><p>But there are some things to consider here before writing the code:</p><ul><li>We should compare children only if node is an element (text nodes can not have children)</li><li>Now we pass reference to <strong><em>current node </em></strong>as parent</li><li>We should compare all children one by one — even if at some point we will have `undefined` — it is ok — our function can handle that</li><li>And finally <strong><em>index </em></strong>— it is just index of child node in `children` array</li></ul><pre>function updateElement($parent, newNode, oldNode, index = 0) {<br>  if (!oldNode) {<br>    $parent.appendChild(<br>      createElement(newNode)<br>    );<br>  } else if (!newNode) {<br>    $parent.removeChild(<br>      $parent.childNodes[index]<br>    );<br>  } else if (changed(newNode, oldNode)) {<br>    $parent.replaceChild(<br>      createElement(newNode),<br>      $parent.childNodes[index]<br>    );<br>  } else if (newNode.type) {<br>    const newLength = newNode.children.length;<br>    const oldLength = oldNode.children.length;<br>    for (let i = 0; i &lt; newLength || i &lt; oldLength; i++) {<br>      updateElement(<br>        $parent.childNodes[index],<br>        newNode.children[i],<br>        oldNode.children[i],<br>        i<br>      );<br>    }<br>  }<br>}</pre><h3>Put That All Together</h3><p>Yeah, this is it. We’re there. I’ve put all the code into JSFiddle and the implementation part took really 50 LOC — as I promised you. Go ahead and play with it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fjsfiddle.net%2Fdeathmood%2F0htedLra%2Fembed%2Fjs%252Cresult%2F&amp;src=https%3A%2F%2Fjsfiddle.net%2Fdeathmood%2F0htedLra%2Fembedded%2F&amp;type=text%2Fhtml&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/f53d7729b1c57f1209348683ff405c0f/href">https://medium.com/media/f53d7729b1c57f1209348683ff405c0f/href</a></iframe><p>Open up Developer Tools and watch changes applied when you press `Reload` button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*e1s_Zc_fVxL3i0un2ZNEtg.gif" /></figure><h3>Conclusion</h3><p>Congratulations! We’ve done that. We’ve written our Virtual DOM implementation. And it works. I hope that, having read this article, you understood basic concepts of how Virtual DOM should work and how React works under the hood.</p><p>However there are some things that were not highlighted here (I will try to cover them in future articles):</p><ul><li>Setting element attributes (props) and diffing/updating them</li><li>Handling events — adding event listeners to our elements</li><li>Making our Virtual DOM work with components, like React</li><li>Getting references to real DOM nodes</li><li>Using Virtual DOM with libraries that directly mutate real DOM — like jQuery and its plugins</li><li>and even more…</li></ul><h3>P.S.</h3><p>If there any errors in code or article, or if there are any optimizations I can do to this code — feel free to express them in comments :)) And sorry for my English :)</p><blockquote>UPDATE: The second article about setting props &amp; events in Virtual DOM is <a href="https://medium.com/@deathmood/write-your-virtual-dom-2-props-events-a957608f5c76">here</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee74acc13060" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>