Edit in GitHubLog an issue

Lesson 4: Setup the Todo component

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

Similarly 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:

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

Component properties

The component will accept 3 properties:

  • name to identify the todo list name
  • todo which holds the todo id, text value and checked status.
  • onUpdate which is the callback function invoked whenever the todo item is updated.
Copied to your clipboard
function Todo({ name, todo, onUpdate }) {
// ...
}

Updating a todo item

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

Copied to your clipboard
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. We'll also update the value state with setValue() and invoke the callback function onUpdate on every input change. onUpdate takes 2 parameters: the todo list name and the todo object.

Copied to your clipboard
<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 exactly the same for Checkbox.

Copied to your clipboard
<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're using the Flex layout to align the Checkbox with the TextField and we're done with our Todo component.

See the full component code here.

Todo

  • Privacy
  • Terms of Use
  • Do not sell or share my personal information
  • AdChoices
Copyright © 2024 Adobe. All rights reserved.