You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
2.5 KiB
Plaintext

# Render: Putting Elements on the Screen
There are now only two major puzzles remaining in our quest for our own React. The next piece is: `render`. How do we go from our JSM tree of nodes, to actually displaying something on screen? To do that we will explore the `render` method.
The signature for our `render` method should be familiar to you:
{format: "javascript"}
```
function render(element, container)
```
This is the same signature as that of React itself. We begin by just focusing on the initial render. In pseudocode it looks like this:
{format: "javascript"}
```
function render(element, container) {
const domElement = createDOMElement(element);
setProps(element, domElement);
renderChildren(element, domElement);
container.appendChild(domElement);
```
Our DOM element is created first. Then we set the properties, render children elements, and finally append the whole tree to the container.
Now that we have an idea of what to build we will work on expanding the pseudocode until we have our own fully functional `render` method using the same general algorithm React uses. In our first pass we will focus on the initial render and ignore reconciliation.
I> Reconciliation is basically React's "diffing" algorithm. We will be exploring it after we work out the initial render.
{format: "javascript"}
```
function render(element, container) {
const { type, props } = element;
// create the DOM element
const domElement = type === 'TEXT' ?
document.createTextNode(props.nodeValue) :
document.createElement(type);
// set its properties
Object.keys(props)
.filter((key) => key !== 'children')
.forEach((key) => domElement[key] = props[key]);
// render its children
props.children.forEach((child) =>
render(child, domElement));
// add our tree to the DOM!
container.appendChild(domElement);
}
```
The `render` method starts by creating the DOM element. Then we need to set its properties. To do this we first need to filter out the `children` property and then we simply loop over the keys, setting each property directly. Following that, we render each of the children by looping over them and recursively calling `render` on each child with the `container` set to the current DOM element (which is each child's parent).
Now we can go all the way from our JSX-like notation to a rendered tree in the browser's DOM! But so far we can only add things to our tree. To be able to remove and modify the tree we need one more part: reconciliation.