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

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 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? We do this by exploring 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 the children elements, and finally append the whole tree to the container.
Now that we have an idea of what to build well work on expanding the pseudocode until we have our own fully functional `render` method by using the same general algorithm that React uses. In our first pass well focus on the initial render and ignore reconciliation.
I> Reconciliation is basically React's "diffing" algorithm. Well 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.