Lesson 4: Setup the Todo component

In this lesson, we'll create a Todo React component composed of only two React Spectrum components: Checkbox and TextField.

In a way similar to lesson 3, we'll create the React component file under web-src/src/components/ and name it Todo.js.

Import React Spectrum components

This component will make use of several React Spectrum components:

import { Flex, Checkbox, TextField } from '@adobe/react-spectrum';

Component properties

The component will accept three properties:

function Todo({ name, todo, onUpdate }) {
  // ...
}

Updating a to-do item

Again, we're going to use the State hook useState to declare two state variables, bind one to the Checkbox and the other to the Textfield:

const [value, setValue] = useState(todo.value);
const [isDone, setIsDone] = useState(todo.done);

Here we use the todo properties value and done to define the default state values.

Next we'll bind the value state to the TextField, update the value state with setValue(), and invoke the callback function onUpdate on every input change. onUpdate takes 2 parameters: the to-do list name and the todo object.

<TextField
    isDisabled={isDone}
    aria-label="Todo"
    width="100%"
    value={value}
    onChange={async (value) => {
      todo.value = value;
      setValue(value);

      onUpdate && (await onUpdate(name, todo));
    }}
    isQuiet
/>

We'll do the same for Checkbox:

<Checkbox
    aria-label="done"
    isSelected={isDone}
    onChange={async (value) => {
      todo.done = value;
      setIsDone(value);

      onUpdate && (await onUpdate(name, todo));
    }}
    isEmphasized
    value={value}
/>

Full component

Finally, we use the Flex layout to align the Checkbox with the TextField and finish our To-do component.

See the full component code here.

Todo