Editable List
This example demonstrates how to build an editable list in the Scripting app using List
, ForEach
, and EditButton
components. The list supports item deletion and reordering with built-in editing controls.
Overview
You will learn how to:
- Display a list of items using
ForEach
- Enable deletion and reordering of items
- Use
EditButton
to toggle editing mode
- Handle state updates using
useState
Example Code
1. Import Required Modules
1import { Color, EditButton, ForEach, List, Navigation, NavigationStack, Script, Text, useState } from "scripting"
2. Define Component State
The list is initialized with an array of Color
strings:
1const [colors, setColors] = useState<Color[]>([
2 "red",
3 "orange",
4 "yellow",
5 "green",
6 "blue",
7 "purple",
8])
3. Handle Item Deletion
The onDelete
function removes items from the list based on selected indices:
1function onDelete(indices: number[]) {
2 setColors(colors.filter((_, index) => !indices.includes(index)))
3}
4. Handle Item Reordering
The onMove
function repositions selected items to a new offset in the list:
1function onMove(indices: number[], newOffset: number) {
2 const movingItems = indices.map(index => colors[index])
3 const newColors = colors.filter((_, index) => !indices.includes(index))
4 newColors.splice(newOffset, 0, ...movingItems)
5 setColors(newColors)
6}
5. Build the Editable List
The main UI is constructed using a NavigationStack
and a List
containing a ForEach
loop. The EditButton
is added to the toolbar to enable editing mode:
1return <NavigationStack>
2 <List
3 navigationTitle={"Editable List"}
4 navigationBarTitleDisplayMode={"inline"}
5 toolbar={{
6 confirmationAction: [
7 <EditButton />,
8 ]
9 }}
10 >
11 <ForEach
12 count={colors.length}
13 itemBuilder={index =>
14 <Text
15 key={colors[index]} // A unique key is required!
16 >{colors[index]}</Text>
17 }
18 onDelete={onDelete}
19 onMove={onMove}
20 />
21 </List>
22</NavigationStack>
6. Launch the View
1async function run() {
2 await Navigation.present({
3 element: <Example />
4 })
5
6 Script.exit()
7}
8
9run()
Key Components
- List: Displays a scrollable, editable list of items.
- ForEach: Dynamically generates views based on item count.
- EditButton: Automatically enables editing mode in the list when tapped.
- onDelete / onMove: Callback functions triggered during item removal or reordering.
- useState: Tracks the current array of items in the list.
Notes
- Always provide a unique
key
for each item in ForEach
to ensure correct rendering.
- Reordering and deletion are only available while in editing mode, which is toggled using
EditButton
.
Use Cases
- Reorderable lists (e.g., task prioritization)
- Editable collections (e.g., color palette, items, settings)
- Dynamic UI that responds to user input
This example provides a flexible foundation for interactive lists in your custom scripts or tools.