Ronaldo Vitto Lewerissa

Software engineering learning documentation.

React's .createElement()

I'm trying to dig some of React's API. This is one of them. I refer to Paul O Shannesy's video on Building React from Scratch.

Due to JSX we don't actually write this by ourselves, but know that JSX will compiles to vanilla JavaScript which uses this API.

function createElement(type, config, children, [children2, ...]) {  
  // Clone the passed in config (props). In React we move some special props off of this object (keys, refs).
  let props = Object.assign({}, config);

  // Build props.children. We'll make it an array if we have more than 1.
  let childCount = arguments.length - 2;
  if (childCount === 1) {
    props.children = children;
  } else if (childCount > 1) {
    props.children = [].slice.call(arguments, 2);
  }

  return {
    type,
    props
  };
}

The type parameter is a string, config is an object, and the children are another createElement() invocation result.

Children of the returned object will be placed inside of the props key, it can be an array or not depending on the number of children.

Written by Ronaldo Vitto Lewerissa

Read more posts by this author.