React Nx Tutorial - Step 3: Display Todos

Nx.dev Tutorial | React | Step 3: Display Todos

Great! You have a failing E2E test. Now you can make it pass!

The best way to work with Cypress is to keep the failing E2E test running while working on the app. This helps you see the progress you are making.

Show Todos

Open apps/todos.

To make the first assertion of the e2e test pass, update apps/todos/src/app/app.tsx:

1import React, { useState } from 'react';
2
3interface Todo {
4  title: string;
5}
6
7export const App = () => {
8  const [todos, setTodos] = useState<Todo[]>([
9    { title: 'Todo 1' },
10    { title: 'Todo 2' },
11  ]);
12
13  return (
14    <>
15      <h1>Todos</h1>
16      <ul>
17        {todos.map((t) => (
18          <li className={'todo'}>{t.title}</li>
19        ))}
20      </ul>
21    </>
22  );
23};
24
25export default App;

Rerun the specs by clicking the button in the top right corner of the left pane. Now the test will fail while trying to find the add todo button.

Add Todos

Add the add-todo button with the corresponding click handler.

1import React, { useState } from 'react';
2
3interface Todo {
4  title: string;
5}
6
7export const App = () => {
8  const [todos, setTodos] = useState<Todo[]>([
9    { title: 'Todo 1' },
10    { title: 'Todo 2' },
11  ]);
12
13  function addTodo() {
14    setTodos([
15      ...todos,
16      {
17        title: `New todo ${Math.floor(Math.random() * 1000)}`,
18      },
19    ]);
20  }
21
22  return (
23    <>
24      <h1>Todos</h1>
25      <ul>
26        {todos.map((t) => (
27          <li className={'todo'}>{t.title}</li>
28        ))}
29      </ul>
30      <button id={'add-todo'} onClick={addTodo}>
31        Add Todo
32      </button>
33    </>
34  );
35};
36
37export default App;

The tests should pass now.