Forward Advance Learning

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:

  1. A string - which will append a text node
  2. A React Element - which will append a child
  3. A Component (more on this later)
  4. 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.

See the Pen React Hello World Demo by Nicholas Johnson (@superluminary) on CodePen.

Change the element to an h2. Change the text to something more personal.

Alternately, we can pass an element as a child. Here we have an em inside an h1.

See the Pen React Nested Element Demo by Nicholas Johnson (@superluminary) on CodePen.

Put an em inside an h1 inside a header element.

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:

See the Pen React Nested Elements Demo by Nicholas Johnson (@superluminary) on CodePen.

Add a sidebar with an unordered list inside of it.

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:

See the Pen React List Demo by Nicholas Johnson (@superluminary) on CodePen.

Try and change the code so it outputs a table. Don't worry about the `key` warnings yet.

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. class is a keyword in JavaScript, so we use the className attribute instead.

See the Pen React DOM Attributes Demo by Nicholas Johnson (@superluminary) on CodePen.

Come up with a list of your favourite websites. Now try to output them as a clickable list of links.

Exercise - A little DOM

Here's a list of villains.

  • Godzilla
  • Eye of Sauron
  • Voldemort
  • Saruman
  • Dalek

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.

Extension

Hyperlink the vilains to their associated Wikipedia pages.

Try to do it without referring to the docs. We're aiming for finger knowledge here.