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
.
This component will make use of several React Spectrum components:
import { Flex, Checkbox, TextField } from '@adobe/react-spectrum';
The component will accept three properties:
name
to identify the to-do list nametodo
which holds the to-do ID, text value and checked status.onUpdate
which is the callback function invoked whenever the todo item is updated.
function Todo({ name, todo, onUpdate }) {
// ...
}
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}
/>
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.