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!
You’ll find that React.createElement()
is the most used function in any React app. Before long, you’ll know it back to front.