Rendering

Elements are the smallest building blocks of React apps.

An element describes what you want to see on the screen

Before diving in to see how these are created in React, let’s take a look at how DOM elements are generally created using plain JavaScript:

// First, we create the element
const element = document.createElement('button');

element.setAttribute('type', 'submit');
element.innerHTML = 'Click me!';

// Then, we append it to the DOM
document.body.appendChild(element);

React.createElement()

Creating elements in React has many similarities to creating elements in the DOM. We need to specify the type of element we want to create, give it certain parameters (called props in React), and the children that should be rendered within our element.

React.createElement('button');
// -> <button></button>

React.createElement('button', { type: 'submit' });
// -> <button type="submit"></button>

React.createElement('button', { className: 'primary', type: 'submit' });
// -> <button class="primary" type="submit"></button>

React.createElement('button', { className: 'primary', type: 'submit' }, 'Click me!');
// -> <button class="primary" type="submit">Click me</button>

Notice how the HTML class attribute has to be set via the className property in React. This is because class is a reserved keyword in JavaScript.

Note that React elements are a lightweight representation of the DOM, and are not actual DOM elements. They are represented as plain objects and are cheap to create.

ReactDOM

React is split into two different packages, react and react-dom. The react-dom package provides DOM-specific methods that can be used at the top level of your app to render React elements into DOM elements.

ReactDOM.render()

The ReactDOM.render() method is used to render React Elements to the DOM, and takes two arguments:

  • The ReactElement to render

  • The DOM node we want to render into (the “entry point”)

const element = React.createElement('h1', {className: 'heading'}, 'Hello World!');

ReactDOM.render(
  element,
  document.getElementById('container')
);

Last updated