React
Rendering Elements
Unlike browser DOM elements, React elements are plain objects, and are cheap to create.
Internal navigation
You can visit this post, or this page, go back to the homepage or just back to the archive.
Rendering an Element into the DOM
Let’s say there is a <div>
somewhere in your HTML file:
<div id="root"></div>
We call this a “root” DOM node because everything inside it will be managed by React DOM.
Applications built with just React usually have a single root DOM node. If you are integrating React into an existing app, you may have as many isolated root DOM nodes as you like.
To render a React element into a root DOM node, pass both to ReactDOM.render()
:
const element = <h1>Hello, world</h1>;
ReactDOM.render(element, document.getElementById('root'));
It displays “Hello, world” on the page.
Updating the Rendered Element
React elements are immutable. Once you create an element, you can’t change its children or attributes. An element is like a single frame in a movie: it represents the UI at a certain point in time.
With our knowledge so far, the only way to update the UI is to create a new element, and pass it to ReactDOM.render()
.
Consider this ticking clock example:
function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(element, document.getElementById('root'));}
setInterval(tick, 1000);
It calls ReactDOM.render()
every second from a setInterval()
callback.