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:
- Flex for the layout.
- TextField the input field for the todo value.
- Checkbox to check a todo which is done.
Copied to your clipboardimport { Flex, Checkbox, TextField } from '@adobe/react-spectrum';
Component properties
The component will accept 3 properties:
name
to identify the todo list nametodo
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 clipboardfunction 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 clipboardconst [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<TextFieldisDisabled={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<Checkboxaria-label="done"isSelected={isDone}onChange={async (value) => {todo.done = value;setIsDone(value);onUpdate && (await onUpdate(name, todo));}}isEmphasizedvalue={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.