Skip to content

Latest commit

 

History

History
110 lines (81 loc) · 2.45 KB

lesson_3.md

File metadata and controls

110 lines (81 loc) · 2.45 KB

Lesson 3 - components

Elements

So far we've created a single element. This is roughly equivalent to a single HTML DOM node containing only text.

What if we want to make the word "Hello" italic:

Hello, react!

We can start nesting elements:

ReactDOM.render(
  React.createElement('span', null,
    React.createElement('i', null, 'Hello'),
    ', react!'
  ),
  document.getElementById('app')
)

If you pop that into our lib/app.js, you'll see: Hello, react!

Excellent, we can render static text in a hierarchical way.

If we had more than one of these elements, say in a list, we can render them out like:

ReactDOM.render(
  React.createElement('ul', null,
    React.createElement('li', null,
      React.createElement('i', null, 'Hello'),
      ', react!'
    ),
    React.createElement('li', null,
      'And hello ',
      React.createElement('b', null, 'again')
    )
  ),
  document.getElementById('app')
)

It looks like we're building up a menu, one which needs a little more functionality such as selecting an item, hovering, etc.

To add interactive functionality in React, there is the concept of components.

Components

We're going to start with what react calls Pure Functional Components. These are very similar to the View Template Functions we're already familiar with.

function MyComponent() {
  return // ....
}

Note that component names must start with an upper case, and must return a single element:

function MenuItem() {
  return React.createElement('li', null, 'Menu Item')
}

Now we can use MenuItem in place of the 'li' in React.createElement('li', ....

It's about time for our first challenge!

Challenge 1

Can you create a <ul> containing 2 menu items using this new component?

<ul>
  <li>Menu Item</li>
  <li>Menu Item</li>
</ul>

Resources

Once all done, keep going with Lesson 4 - modules.


Lesson 2 - react « | Home | » Lesson 4 - modules

TOC