React Elements are just objects

Elements are just objects

At it’s simplest, React is a library for creating and updating HTML elements.

ReactDOM.render() is the function that actually does the creating and updating. It takes a React Element object that describes what to render, and uses this to update the DOM node that’s passed in as the second argument.

But wait a moment, isn’t React.createElement() creating elements? It is! But maybe not in the way you’d expect.

The React Element objects that React.createElement() returns are just plain old JavaScript objects that describe the DOM nodes that you’d like ReactDOM.render() to create. They’re not DOM nodes, and not added to the document. They’re just objects.

And they look a little something like this:

{
  // The type of element to use. It can be the name of a HTML element,
  // or can be a custom type (which we'll get to later).
  type: 'a',

  // Configures the created HTML element's attributes and children.
  props: {
    href: 'https://xkcd.com/221/',

    // If specified, this will contain the element's content. It can be
    // a string, an array, or another React Element.
    children: {
      type: 'img',
      props: {
        src: "https://imgs.xkcd.com/comics/random_number.png",
        alt: "RFC 1149.5 specifies 4 as the standard IEEE-vetted random number.",
      }
    },
  },
}

The React.createElement() function takes three arguments: type, props, and children. And returns an object just like the one above.

React.createElement(type, props, children)

You can get a feel for this by passing different parts of a returned Element object to console.log(). Try changing it yourself by changing the console.log() statements below!

index.js
index.html
let element =
  React.createElement(
    // The first argument is the element's `type`
    'a',

    // The second argument is the element's `props`
    { href: 'https://xkcd.com/222/' },

    // Any further arguments, if given, are merged into to
    // `props` under the name `children`.
    React.createElement(
      'img',
      {
        src: "https://imgs.xkcd.com/comics/random_number.png",
        alt: "RFC 1149.5 specifies 4 as the standard IEEE-vetted random number.",
      }
    ),
    React.createElement(
      'span',
      null,
      'By Randall Munroe',
    )
  )

// Try logging different parts of the `element` object
console.log(element.props.children[0].type)
console.log(element.props.children[1].props.children)

ReactDOM.render(
  element,
  document.getElementById('root')
)
Build In Progress

    You’ll find that React.createElement() is the most used function in any React app. Before long, you’ll know it back to front.

    Progress to next section.