Understanding The React Source Code — Initial Rendering (Simple Component) III

Holmes He
source code
Published in
7 min readJan 5, 2018
Photo by Matt Kochar on Unsplash

同学,本文也有中文版哦:)

Understanding The React Source Code I
Understanding The React Source Code II
Understanding The React Source Code III (this one)
Understanding The React Source Code IV
Understanding The React Source Code V
Understanding The React Source Code VI
Understanding The React Source Code VII
Understanding The React Source Code VIII
Understanding The React Source Code IX

Last time we completed the platform agnostic logic (a.k.a., upper half) that embeds ReactElement[1] into ReactCompositeComponent[T] and then uses it to derive ReactDOMComponent[ins].

This time I will discuss how a renderable HTML DOM element is created with ReactDOMComponent[ins], and complete the JSX-to-UI process.

Files used in this article:

renderers/dom/shared/ReactDOMComponent.js: creates the renderable h1 DOM element

renderers/dom/client/utils/DOMLazyTree.js: adds the h1 to the DOM tree

renderers/dom/client/ReactMount.js: the cross point revisited by the above two actions

`ReactDOMComponent.mountComponent()` — create the DOM element with `document.createElement()`

It calls HTML DOM APIs and hits the bottom.

The designated data structure:

The call stack in action:

|=ReactMount.render(nextElement, container, callback)     ___
|=ReactMount._renderSubtreeIntoContainer() |
|-ReactMount._renderNewRootComponent() |
|-instantiateReactComponent() |
|~batchedMountComponentIntoNode() upper half
|~mountComponentIntoNode() (platform agnostic)
|-ReactReconciler.mountComponent() |
|-ReactCompositeComponent.mountComponent() |
|-ReactCompositeComponent.performInitialMount() |
|-instantiateReactComponent() _|_
/* we are here*/ |
|-ReactDOMComponent.mountComponent( lower half
transaction, (HTML DOM specific)
hostParent, |
hostContainerInfo, |
context, (same) |
) |

ReactDOMComponent.mountComponent() is a fairly long and complex function. So I dye the required fields for easily back tracing their origins. Next we look at how exactly it is implemented.

mountComponent: function (
transaction, // scr: -----> not of interest
hostParent, // scr: -----> null
hostContainerInfo, // scr: -----> ReactDOMContainerInfo[ins]
context // scr: -----> not of interest
) {
// scr: --------------------------------------------------------> 1)
this._rootNodeID = globalIdCounter++;
this._domID = hostContainerInfo._idCounter++;
this._hostParent = hostParent;
this._hostContainerInfo = hostContainerInfo;
var props = this._currentElement.props; switch (this._tag) { // scr: ---> no condition is met here
...
}
... // scr: -----> sanity check// We create tags in the namespace of their parent container, except HTML
// tags get no namespace.
var namespaceURI;
var parentTag;
if (hostParent != null) { // scr: -----> it is null
...
} else if (hostContainerInfo._tag) {
namespaceURI = hostContainerInfo._namespaceURI; // scr: -------> "http://www.w3.org/1999/xhtml"
parentTag = hostContainerInfo._tag; // scr: ------> "div"
}
if (namespaceURI == null ||
namespaceURI === DOMNamespaces.svg &&
parentTag === 'foreignobject'
) { // scr: -----> no
...
}
if (namespaceURI === DOMNamespaces.html) {
if (this._tag === 'svg') { // scr: -----> no
...
} else if (this._tag === 'math') { // scr: -----> no
...
}
}
this._namespaceURI = namespaceURI; // scr: ---------------------> "http://www.w3.org/1999/xhtml"... // scr: ------> DEV code var mountImage; if (transaction.useCreateElement) { // scr: ---------------------> transaction related logic, we assume it is true
var ownerDocument = hostContainerInfo._ownerDocument;
var el;
if (namespaceURI === DOMNamespaces.html) {
if (this._tag === 'script') { // scr: -----> no
...
} else if (props.is) { // scr: -----> no
...
} else {
// Separate else branch instead of using `props.is || undefined` above becuase of a Firefox bug.
// See discussion in https://github.com/facebook/react/pull/6896
// and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
// scr: --------------------------------------------------------> 2)
// scr: ---------> HTML DOM API
el = ownerDocument.createElement(this._currentElement.type);
}
} else { // scr: ------> no
...
}
// scr: --------------------------------------------------------> 3)
ReactDOMComponentTree.precacheNode(this, el); // scr: --------> doubly link (._hostNode & .internalInstanceKey)
this._flags |= Flags.hasCachedChildNodes; // scr: ------------>
bit wise its flags
// scr: --------------------------------------------------------> 4)
if (!this._hostParent) { // scr: ------> it is the root element
DOMPropertyOperations.setAttributeForRoot(el); // scr: -----> data-reactroot
}
// scr: --------------------------------------------------------> 5)
this._updateDOMProperties( //*6
null,
props,
transaction
); // scr: --------------------------> style:{ “color”: “blue” }
// scr: --------------------------------------------------------> 6)
var lazyTree = DOMLazyTree(el); // scr: ------> DOMLazyTree[ins]
// scr: --------------------------------------------------------> 7)
this._createInitialChildren( //*7
transaction,
props,
context,
lazyTree
); // scr: --------------------------> textContent:‘hello world’

mountImage = lazyTree;
} else { // if (transaction.useCreateElement)
...
}
switch (this._tag) { // scr: ---> no condition is met here
...
}
return mountImage;
}
ReactDOMComponent@renderers/dom/shared/ReactDOMComponent.js

1) It initializes some of the ReactDOMComponent[ins]’s properties with the parameters and global variables. Then all the if conditions are passed until

2) The HTML DOM API document.createElement() is called to create an h1 DOM element.

3) ReactDOMComponentTree.precacheNode() is used to create a doubly link between ReactDOMComponent[ins] and h1 DOM element, it links ReactDOMComponent[ins]._hostNode to the h1 DOM element and the element’s internalInstanceKey back to ReactDOMComponent[ins].

4) As a null _hostParent indicates an internal root component, DOMPropertyOperations.setAttributeForRoot() setelement.data-reactroot to empty string “”, to mark a root element externally.

5) _updateDOMProperties is a complex method. For now we only need to know the method extracts { “color”: “blue” } from ReactDOMComponent[ins]._currentElement.props and attaches it to the DOM’s style attribute. We will come back to this method in more detail when discussing “setState() triggered UI update”. Search for

*6

in this text when you need check when this function is used first time.

6) Instantiates a DOMLazyTree[ins].

7) _createInitialChildren is another complex method. For now we only need to know the method extracts ‘hello world’ from ReactDOMComponent[ins]._currentElement.children and attaches it to the DOM’s textContent. We will come back to this method in more detail when discussing “composite component rendering”. You can search for

*7

then.

Then DOMLazyTree[ins] is returned all the way back to the cross point discussed in the last post — mountComponentIntoNode().

`mountImageIntoNode()` — mount the DOM into the container node

First lemme copy back the stack frame from the last post.

|=ReactMount.render(nextElement, container, callback)     ___
|=ReactMount._renderSubtreeIntoContainer() |
|-ReactMount._renderNewRootComponent() |
|-instantiateReactComponent() |
|~batchedMountComponentIntoNode() upper half
|~mountComponentIntoNode( (platform agnostic)
wrapperInstance, // scr: -> not of interest now |
container, // scr: --> document.getElementById(‘root’)
transaction, // scr: --> not of interest |
shouldReuseMarkup, // scr: -------> null |
context, // scr: -------> not of interest
) |
|-ReactReconciler.mountComponent() |
|-ReactCompositeComponent.mountComponent() |
|-ReactCompositeComponent.performInitialMount() |
|-instantiateReactComponent() _|_
|-ReactDOMComponent.mountComponent() |
/* we are here */ lower half
|-_mountImageIntoNode() (HTML DOM specific)
markup, // scr: --> DOMLazyTree[ins] |
container, // scr: --> document.getElementById(‘root’)
wrapperInstance, // scr:----> same |
shouldReuseMarkup, // scr:--> same |
transaction, // scr: -------> same |
) _|_

Now the implementation:

_mountImageIntoNode: function (
markup,
container,
instance,
shouldReuseMarkup,
transaction)
{
if (shouldReuseMarkup) { // scr: -------> no

}
if (transaction.useCreateElement) {//scr:>again, assume it is true
while (container.lastChild) { // scr: -------> null

}
// scr: -------------------------> the only effective line this time
DOMLazyTree.insertTreeBefore(container, markup, null);
} else {

}
… // scr: DEV code
}
ReactMount@renderers/dom/client/ReactMount.js

Despite the seemly complexity, there is only one line that is effective, that calls insertTreeBefore.

var insertTreeBefore = createMicrosoftUnsafeLocalFunction(function (
parentNode, // scr: -----> document.getElementById(‘root’)
tree, // scr: -----> DOMLazyTree[ins]
referenceNode // scr: -----> null
) {
if (tree.node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE ||
tree.node.nodeType === ELEMENT_NODE_TYPE &&
tree.node.nodeName.toLowerCase() === 'object' &&
(tree.node.namespaceURI == null ||
tree.node.namespaceURI === DOMNamespaces.html)) { // scr:->no
...
} else {
parentNode.insertBefore(tree.node, referenceNode);
insertTreeChildren(tree); // scr: -> returned directly in Chrome
}
});
DOMLazyTree@renderers/dom/client/utils/DOMLazyTree.js

Inside this function, the only one line that is effective is :

parentNode.insertBefore(tree.node, referenceNode);

which is another HTML DOM API that inserts DOMLazyTree[ins].node (i.e., the h1 DOM element) into the #root element, as instructed with the JSX statement in the very beginning :


ReactDOM.render(
<h1 style={{“color”:”blue”}}>hello world</h1>,
document.getElementById(‘root’)
);

A conclusion so far

`React.createElement()` — create a `ReactElement`
`_renderSubtreeIntoContainer()` — attach `TopLevelWrapper` to the `ReactElement[1]`
`instantiateReactComponent()` — create a `ReactCompositeComponent` using `ReactElement[2]`
`ReactCompositeComponent.mountComponent()` — initialize `ReactCompositeComponent[T]`
`ReactCompositeComponent.performInitialMount()` — create a `ReactDOMComponent` from `ReactElement[1]`
`ReactDOMComponent.mountComponent()` — create the DOM element with `document.createElement()
`mountImageIntoNode()` — mount the DOM into the container node

End notes

In this series I focus on a very primitive operation — h1 component mount which nonetheless walk through the complete critical-path of the rendering process. I think this quick end-to-end tour can help establishing an initial knowledge base and confidence for further exploring the uncharted areas. I assume it’s gonna be more intricate and intriguing.

Though good effort is made to simulate a real experience that includes a clear goal and a concrete outcome, it is highly recommended to try the full version of the source code by debugging it in Chrome directly.

React 16 uses fiber reconciler as the new architecture. Go ahead if you can not wait to check it out. Happy hacking!

Related articles and resource:

https://reactjs.org/docs/implementation-notes.htm

https://hackernoon.com/build-your-own-react-48edb8ed350d

https://medium.com/@ericchurchill/the-react-source-code-a-beginners-walkthrough-i-7240e86f3030

I hope you like this read. If so, please clap for it or follow me on Medium. Thanks, and I hope to see you the next time.👋

Originally published at holmeshe.me.

--

--