Demo

To start off our todo application we are going to follow the steps outlined in Thinking in React. The first step of the process is to break our application into a component hierarchy. For this app, we’re going to keep it simple and just use four parts.

  • TodoHeader
  • TodoList
  • TodoListItem
  • TodoFooter

We could go a lot deeper into creating buttons, inputs and checkboxes, but this is a great place to start. Often you’ll want to start with a single large control and then break it up into smaller pieces.

TodoApp

  1. import React from 'react';
  2. import { TodoFooter } from './components/TodoFooter';
  3. import { TodoHeader } from './components/TodoHeader';
  4. import { TodoList } from './components/TodoList';
  5. export class TodoApp extends React.Component {
  6. render() {
  7. return (
  8. <div>
  9. <TodoHeader />
  10. <TodoList />
  11. <TodoFooter />
  12. </div>
  13. );
  14. }
  15. }

We’ll start off with all of the files scaffolded and imported into our App. This will let us dive right into each control and see updates quickly.

TodoHeader

Our objective for now is to create a static version of our application, so we’ll copy over the entire header tag from a previous step, minus any function calls we added.

Note that since this is React we had to change class to className, but nothing else changes.

  1. return (
  2. <header>
  3. <h1>todos</h1>
  4. <div className="addTodo">
  5. <input className="textfield" placeholder="add todo" />
  6. <button className="submit">Add</button>
  7. </div>
  8. <nav className="filter">
  9. <button className="completed">all</button>
  10. <button>active</button>
  11. <button>completed</button>
  12. </nav>
  13. </header>
  14. );

TodoListItem

Any time you see repeated complex elements, that is usually a sign that you should create a new component. With a few props you can typically abstract all of those elements into a single component. This is certainly the case with todo items.

  1. return (
  2. <li className="todo">
  3. <label>
  4. <input type="checkbox" /> Todo 1
  5. </label>
  6. </li>
  7. );

Note that I’ve removed the title span as it was only needed to make targeting that text easier.

Exercise

If you already have the app running from a previous step, stop it with ctrl+C. Start the app version used in this step by running npm start from the root of the frontend-bootcamp folder. Click the “exercise” link under day 1 step 5 to see results.

TodoFooter

  1. Update the TodoFooter component, copying over the <footer> tag and all of its children
  2. Remove any onclick properties, and change class to className

TodoList

  1. Update the TodoList component like you did with the footer.
  2. Import TodoListItem and add 4 of them inside of the <ul>
  3. Bonus points for using a for loop or using map to create 4 list items based on the array [1,2,3,4]