React Element Rendering
Elements are the smallest building blocks of a React application, used to describe what is displayed on the screen.
const element = <h1>Hello, world!</h1>;
Unlike browser DOM elements, React elements are plain objects, and React DOM ensures that the browser DOM data content matches the React elements.
Rendering Elements into the DOM
First, we add a <div>
with an id="example"
in an HTML page:
<div id="example"></div>
All content within this div will be managed by React DOM, so we call it the "root" DOM node.
When developing a React application, we usually define only one root node. However, if you are introducing React into an existing project, you might need to define separate React root nodes in different parts.
To render a React element into the root DOM node, we pass them to the ReactDOM.render()
method to render them on the page:
Example
const element = <h1>Hello, world!</h1>;
ReactDOM.render(
element,
document.getElementById('example')
);
Updating Rendered Elements
React elements are immutable. Once an element is created, you cannot change its content or attributes.
The only way to update the interface is to create a new element and pass it to the ReactDOM.render()
method:
Consider this timer example:
Example
function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(
element,
document.getElementById('example')
);
}
setInterval(tick, 1000);
The above example calls ReactDOM.render()
every second using the setInterval()
method.
We can encapsulate the part to be displayed using a function:
Example
function Clock(props) {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {props.date.toLocaleTimeString()}.</h2>
</div>
);
}
function tick() {
ReactDOM.render(
<Clock date={new Date()} />,
document.getElementById('example')
);
}
setInterval(tick, 1000);
In addition to functions, we can also create an ES6 class of React.Component
, which encapsulates the elements to be displayed. Note that in the render()
method, we need to replace props
with this.props
:
Example
class Clock extends React.Component {
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.props.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
function tick() {
ReactDOM.render(
<Clock date={new Date()} />,
document.getElementById('example')
);
}
setInterval(tick, 1000);
>
React Only Updates What's Necessary
It's worth noting that React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.