Reputation: 1167
I am learning reactjs and stumbled upon this peculiar detail, see my image below. It is the react demo showing how reactjs only update the parts of the dom which have changed.
function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
// highlight-next-line
ReactDOM.render(element, document.getElementById('root'));
}
setInterval(tick, 1000);
Live example: https://codepen.io/pen?&editors=0010
As you can see, when the clock ticks, only the second part of the text gets updated. In my experience, I can update the content of a single html-element, meaning my code would update the entire text of the h2-element. Here it really looks like there are three text elements inside the h2-element. I must be missing some basic knowledge here!
As it looks, it seems to be possible to address/find and update a sub-text as if it is an element of its own, in this case, the "3:05:42 PM" text piece. How do you do this in plain javascript?
Upvotes: 1
Views: 816
Reputation: 53991
How React does this specifically is a question for the documentation and the code itself, however we can have a look at how we might do this in plain JS with a simulation such as this one:
let t1 = document.createTextNode("The seconds are: ");
let t2 = document.createTextNode(new Date().getSeconds());
let t3 = document.createTextNode(". Isn't it cool?");
const content = document.getElementById("content");
content.appendChild(t1);
content.appendChild(t2);
content.appendChild(t3);
setInterval(() => {
let nextT2 = document.createTextNode(new Date().getSeconds());
content.replaceChild(nextT2, t2);
t2 = nextT2;
}, 1000);
https://codesandbox.io/s/replace-text-node-h4ivy
The idea here is that we're able to create the text as separate text nodes which we can later replace directly. In the case of React, they could - if they so chose to - create each part of the text as a separate text node. React will already know that the content is in 3 parts (text, code-block, text), so it seems reasonable to conclude that they may choose to append it to the DOM as 3 text nodes.
Our setInterval
here is representing the final stages of some process that eventually updates the DOM. If you check in the dev tools you'll probably see only the numbers updating, similar to how you see it updating in React.
Upvotes: 2