Exercise 1: Solution

In notebook:
FrontEndMasters React
Created at:
libraries React JavaScript
Note: there’s also a notes.js file in each exercise folder that helps with the syntax, etc.

Note 2: You don’t have to wrap your JSX in parentheses (when you return them for example). Just there to help him visually separate the JSX block.

Shows how he does the solutions:
// Excercise:
// Render `DATA` to the page
// - put the title in an h1
// - only render mexican food (hint: arrays have a "filter" method)
// - sort the items in alphabetical order by name
//   (might want to use `sort-by` https://github.com/staygrimm/sort-by#example)

var React = require('react');
var sortBy = require('sort-by');

var DATA = {
  title: 'Menu',
  items: [
    { id: 1, name: 'tacos', type: 'mexican' },
    { id: 2, name: 'burrito', type: 'mexican' },
    { id: 3, name: 'tostada', type: 'mexican' },
    { id: 4, name: 'hush puppies', type: 'southern' }

var Menu = React.createClass({
  render () {
    // 3. ++++ Create the items list
    var items = DATA.items.map(function(item) {
      return <li>{item.name}</li>;
    // 1. ++++ Just return the title
   return ( <div>
      // 2. ++++ Then the list
    </div> );

React.render(<Menu/>, document.body, () => {
Now almost all assertions are OK. Needs to filter out the ‘hush puppies’:
    // 4. ++++ Filter the list
    var items = DATA.items.filter((item) => {
      return item.type === 'mexican';
    }).map(function(item) {
      return <li>{item.name}</li>;
And finally, he needs to order list alphabetically:
    // 5. ++++ Order the list
    var items = DATA.items.filter((item) => {
      return item.type === 'mexican';
    }).sort(sortBy('name')).map(function(item) {
      return <li>{item.name}</li>;
He did import a sortBy library to simplify sorting. (​var sortBy = require(’sort-by’);​)

Now all of his assertions are passing.

This exercise demonstrates, that if you know JavaScript, React will be easy. Just need to get one or two conventions.
- Why do you need to wrap everything in a <div>?
- React expects you: “Adjacent JSX elements must be wrapped in an enclosing element
You have to have a root element in each component. 

Shows a Backbone example:
​Backbone.View.create({tagName: ‘ul’, class: ‘mul’});
Here, Backbone “owns” this element.

- What does the ​return​ returns in ​React.createClass​ above?
- It’s equivalent to ​React.DOM.div()​ It’s a function call that returns a React element.
add ​window.react = React​ so he can inspect it in the console.
He runs  ​var el = React.DOM.div()​ in the console and inspects ​el​. It’s a ​ReactElement​ object.
This is what React uses when it actually renders the page. It has properties like ​props​ etc. So the ​<div>​ JSX is a function call (turned into a function in JSX) that returns a React element.