Updated March 29, 2023
Introduction to React Render
The following articles provide an outline for React Render. In React, Rendering is one of the most important processes used for making the browser to understand the components used. It is used to transform the react components in the Document Object Model (DOM) nodes which help the browser to understand and display the components on the screen. Elements manipulation is quite faster than manipulating DOM. React creates a Virtual DOM which looks the same as a DOM. Now, it allows us to make changes in the running application. React batches all of the changes made in the virtual DOM and compares it to the original DOM, and then it updates whatever has been changed.
Syntax of React Render
To render the element into a room DOM node, we have to pass both of the components
ReactDOM.render()
const element = <h1>Hello, world</h1>;
ReactDOM.render(element, document.getElementById('root'));
Working of React Render
React elements are rendered into a DOM node by using ReactDOM.render. When we call for the first time to reactDOM.render(element, domnode). The contents of the DOM Node are replaced by the Element’s content. Now, if we call the render statement again, it updates the content of the DOM node by the new content from the element.
Examples of React Render
Different examples are mentioned below:
Example #1 – Basic Render in Timer
In the example below, we have used Render using a simple statement ReactDOM.render. The example below focuses on showing the time according to IST (Indian Standard Time).
index.js
import React from "react";
import ReactDOM from "react-dom";
function tick() {
const element = (
<div>
<h2>Current Time in IST is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(element, document.getElementById("root"));
}
setInterval(tick, 1000);
Output:
Example #2 – Render used in List Rendering
In the example below, we have used render before return to import data from the database link in the App.js file. And in index.js, we have imported render from react-dom.
App.js
import React
, { Component } from "react";
import axios from "axios";
export default class App extends Component {
constructor() {
super();
console.log("Constructor");
this.state = {
title: "Heyoo! Welcome to Our Database",
users: []
};
}
callBeforeRender() {
console.log(
"Called after render :( ");
}
async loadData() {
console.log("Load data");
let {
data
} = await axios.get(
"https://jsonplaceholder.typicode.com/users"
);
this.setState({ users: data });
this.callBeforeRender();
}
componentDidMount() {
console.log("Did mount");
setTimeout(() => {
this.loadData();
}, 2000);
}
componentWillUpdate() {
console.log("Will update");
setTimeout(() => {
});
}
render() {
console.log("Render");
return (
<div>
<h1> {this.state.title} </h1>
{this.state.users.map(user => {
return <li>{user.email}</li>;
})}
</div>
);
}
}
index.js
import React from "react";
import { render } from "react-dom";
import Main from "./App";
const App = () => (
<div>
<Main />
</div>
);
render(<App />, document.getElementById("root"));
Output:
Example #3 – Counter using Render
In the example below, a simple counter with an increment of 1 is implemented, and in our index.js file, render is used through ReactDOM.render.
index.js
import React from "react";
import ReactDOM from "react-dom";
function Logger(props) {
console.log(`${props.label} rendered`);
return null;
}
function Counter(props) {
const [count, setCount] = React.useState(0);
const increment = () => setCount(c => c + 1);
return (
<div>
<button onClick={increment}>The Counter Value is {count}</button>
{props.logger}
</div>
);
}
ReactDOM.render(
<Counter logger={<Logger label="counter" />} />,
document.getElementById("root")
);
Output:
Example #4 – Auto Rendering in React
In the example below, render is imported through ‘react-dom’ and used to return the values. The timer automatically increases and tells the time spent by you on the page.
index.js
import React
, { Component } from 'react'
import { render
, createPortal } from 'react-dom'
class Foo extends Component {
componentDidMount () {
this.props.shareState({ foo: 'You have spent time in seconds notified above' })
}
render () {
return (
<div style={{ border: `2.5px solid ${this.props.theme}` }}>
Heyoo! {this.props.append} ({this.props.count})
<p>{this.props.sharedState.foo}</p>
</div>
)
}
}
const target = document.body.appendChild(
document.createElement('div')
)
const Components = props => Object.keys(props.components)
.reduce((reduced, name) => {
const Component = props.components[name]
const className = `.js-component-${name}`
const targets = document.querySelectorAll(className)
return [
...reduced,
[...targets].map(target => createPortal(
<Component {...props} {...target.dataset} />,
target
))
]
}, [])
class App extends Component {
constructor (props) {
super(props)
this.state = {
theme: 'cyan',
count: 0
}
}
componentDidMount () {
setInterval(() => {
this.setState(({ count }) => ({
count: count + 1
}))
}, 1000)
}
render () {
return (
<Components
theme={this.state.theme}
count={this.state.count}
shareState={this.setState.bind(this)}
sharedState={this.state}
components={{
foo: Foo
}}
/>
)
}
}
render(<App />, target)
Output:
Example #5 – Implementing 2 Patterns using Renders in React
In the example below, we have 2 props patterns, i.e Counter and List, and are combined in an application using Render through ReactDOM.render in index.js file.
Counter.js and CounterWrapper.js are the files used to implement the counter, and List.js and ListWrapper.js are the files used to implement the list. Finally, the styling is taken care of using the styles.css file.
Counter.js
import React from "react";
import CounterWrapper from "./CounterWrapper";
const Counter = () => {
return (
<CounterWrapper>
{({ increment
, decrement
, count }) => (
<div>
<div>
<h3>Counter</h3>
</div>
<div>
<p>{count}</p>
<button onClick={() => increment()}>Increasing Value</button>
<button onClick={() => decrement()}>Decreasing Value</button>
</div>
</div>
)}
</CounterWrapper>
);
};
export { Counter as default };
CounterWrapper.js
import React from "react";
class CounterWrapper extends React.Component {
state = {
count: 0
};
increment = () => {
const { count } = this.state;
return this.setState({ count: count + 1 });
};
decrement = () => {
const { count } = this.state;
return this.setState({ count: count - 1 });
};
render() {
const { count } = this.state;
return (
<div>
{this.props.children({
increment: this.increment,
decrement: this.decrement,
count: count
})}
</div>
);
}
}
export { CounterWrapper as default };
List.js
import React from "react";
import ListWrapper from "./ListWrapper";
const List = () => {
return (
<ListWrapper link="https://jsonplaceholder.typicode.com/userss">
{({ list
, isLoading
, error }) => (
<div>
<h2>Error</h2>
{error ? <p>{error.message}</p> : null}
{isLoading ? (
<h2>Updating Status...</h2>
) : (
<ul>
{list.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
)}
</div>
)}
</ListWrapper>
);
};
export { List as default };
ListWrapper.js
import React from "react";
import axios from "axios";
class ListWrapper extends React.Component {
state = {
isLoading: true,
error: null,
list: []
};
fetchData() {
axios
.get(this.props.link)
.then(response => {
this.setState({
list: response.data,
isLoading: false
});
})
.catch(
error => this.setState(
{ error
, isLoading: false
}
)
);
}
componentDidMount() {
this.setState({ isLoading: true }, this.fetchData);
}
render() {
const { children } = this.props;
const ui = typeof children === "function" ? children(this.state) : children;
return <>{ui}</>;
}
}
export { ListWrapper as default };
index.js
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import Counter from "./Counter";
import List from "./List";
class App extends React.Component {
render() {
return (
<div>
<Counter />
<List />
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, document.getElementById("root"));
styles.css
.App {
font-family: 'Times New Roman'
, Times
, serif;
text-align: center;
}
Output:
Conclusion
Based on the above article, we have explained about React Render and its working. We have demonstrated multiple examples to understand how rendering can be used to transform the components into DOM nodes in different situations and requirements of the application.
Recommended Articles
This is a guide to React Render. Here we discuss the introduction, syntax, and working of React Render along with examples and code implementation. You may also have a look at the following articles to learn more –