View on GitHub

react

React[0] + Redux[0] > A brief introduction to React and Redux

React Elements

createElement()

Returns a JavaScript object that describes what should be rendered. Its signature is React.createElement(type, [props], [...children]):

  1. type — a string for a DOM element (e.g. 'div') or a reference to a React component
  2. props — an object of props/attributes (or null if none)
  3. ...children — zero or more child elements/strings (variadic: you can pass as many as you need)

Example:

const element = React.createElement(
  'div',
  null,
  React.createElement('strong', null, 'Hello world!')
);

Note: We can pass multiple parameters as the last argument. Behind the scenes, React will “wrap them” in an array.

Example:

...   
React.createElement('div', null, 'Hello world!', ' More 1...', ' More 2...') 
...

In our examples, if we log element we will have one case where the value of the key children will be a string and the other an array of strings

props:
  children: "Hello world!"

props:
  children: (3) ["Hello world!", " More 1...", " More 2..."]

Alternatively, we can pass an object as the second argument containing: attributes and the own content as the value of the children’s key. Example:

const element = React.createElement(
  'div',
  null,
  React.createElement('div', { role: 'contentinfo', className: 'this-is-a-div', children: ['Hi',' Hola'] })
);

ReactDOM.render()

Let’s first render our previous element.

const element = React.createElement(
  'div',
  null,
  React.createElement('strong', null, 'Hello world!')
);

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

If we inspect our html we will see our DOM node…

<body>
  <div id="root">
  <div><strong>Hello world!</strong></div>
  </div>
</body>

Another example (with components not elements)

Example: src/index.js

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root')
);

Note: Remember React Apps usually have a single root element.

File: public/index.html

<div id="root"></div>

Elements

As we saw previously, we create elements through React.createElement(). An element is a plain JavaScript object that describes what we want to show on the screen — either a DOM node (when type is a string like 'div') or another React component (when type is a component reference). Elements are immutable and cheap to create; React uses them as the input to its reconciliation algorithm.

const element = <div>Im an element!</div>;

Through components (we will cover this on the next chapter) we return the created elements. Let’s go back to our Hello world! example…

const element = React.createElement(
  'div',
  null,
  React.createElement('strong', null, 'Hello world!')
);

const HelloWorld = () => element;

ReactDOM.render(<HelloWorld />, document.getElementById('root'));