Composing a DOM with Vanilla React
The DOM is a tree, things go inside other things, so the React virtual DOM allows us to create a tree too.
The third parameter of createElement can be one of four things:
- A string - which will append a text node
- A React Element - which will append a child
- A Component (more on this later)
- An Array (or perhaps a function call that returns an array)
This means that when we create an element, we can put other elements inside it to build our DOM. Then when we render, the tree will be appended to the page.
Nesting Strings and Elements
We have already seen this. We simply pass a string as the third parameter and it becomes the innerText of the node.
Alternately, we can pass an element as a child. Here we have an em inside an h1.
Nesting an Array of Elements
If the third parameter is an array of elements and strings, they will all be inserted, and can themselves contain their own children:
Generating a list
We can use this to programatically generate a list of elements. Say we have an array of retro spaceships. We might use Array.map to map them into an array of DOM nodes, which could then be passed in as children of another DOM node:
Setting Classes and Attributes.
We can optionally set classes and other attributes on an element. The second parameter can be an object containing a list of attributes that will be applied to the new DOM node.
The exception to this is the class attribute.
className attribute instead.
Exercise - A little DOM
Here's a list of villains.
- Eye of Sauron
Create an index.html file and app.js. Given the list of villains, and without referring to the notes, try to create a little DOM that renders them in a nice table.
Hyperlink the vilains to their associated Wikipedia pages.
Try to do it without referring to the docs. We're aiming for finger knowledge here.