3.1 What is React?
Convert to React
# Background
# React.createElement()
React uses plain JavaScript objects for managing the elements that eventually get rendered to the screen. They are called React Elements (opens new window). The ReactDOM library will use these to render and synchronize with the real DOM Elements.
The function signature is
React.createElement(
type, // a string element name like 'div' or 'span'
props, // an object like { className: 'some-class' }
...children // either plain text, or other React Elements
);
1
2
3
4
5
2
3
4
5
# ReactDOM
The ReactDOM module is responsible to adding, removing and updating real DOM elements to synchronize with the React Elements. Most applications will only need to use the ReactDOM.render()
method once to mount the main application component.
The function signature is
ReactDOM.render(
element, // the React Element that will be mounted to the DOM
container, // the existing DOM element to mount into, e.g. rootElement
callback // optional callback function, rarely used.
);
1
2
3
4
5
2
3
4
5
# Example Activity
Convert the plain JavaScript to use the React.createElement()
and ReactDOM.render()
methods.
It should generate this HTML
<p class="container">Hello World</p>
1
# Code
// Plain JavaScript version
const rootElement = document.getElementById('root');
//
const element = document.createElement('p');
element.className = 'container';
element.textContent = 'Hello World';
//
rootElement.append(element);
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
// Using React
const rootElement = document.getElementById('root');
// const element = document.createElement('div')
// element.className = 'container'
// element.textContent = 'Hello World'
const element = React.createElement(
'p',
{ className: 'container' },
'Hello World'
);
// rootElement.append(element)
ReactDOM.render(element, rootElement);
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# Try adding console.log(element)
... what do you see?
element
is not an normal HTML DOM Element. It is a React Element object.