• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# ForEach
2
3**ForEach** enables rendering of repeated content based on array type data.
4
5> **NOTE**
6>
7> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8
9For details about the development, see [ForEach: Rendering Repeated Content](../../../quick-start/arkts-rendering-control-foreach.md).
10
11## APIs
12
13ForEach(arr: Array\<any\>,itemGenerator: (item: any, index: number) => void,keyGenerator?: (item: any, index: number) => string,)
14
15**ForEach** enables rendering of repeated content based on array type data. It must be used in a container component, and the component it returns must be one allowed inside the container component. For example, for rendering of list items, **ForEach** must be used in the [List](../../../reference/apis-arkui/arkui-ts/ts-container-list.md) component.
16
17**Widget capability**: This API can be used in ArkTS widgets since API version 9.
18
19**Atomic service API**: This API can be used in atomic services since API version 11.
20
21**System capability**: SystemCapability.ArkUI.ArkUI.Full
22
23**Parameters**
24
25| Name       | Type                                   | Mandatory| Description                                                        |
26| ------------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
27| arr           | Array\<Object\>                         | Yes  | Data source, which is an array.<br>**NOTE**<br>- You can set this parameter to an empty array. In this case, no child component is created.<br>- You can also set this parameter to a function whose return value is an array, for example, **arr.slice (1, 3)**. However, the set function cannot change any state variables including the array itself. For example, **Array.splice**, **Array.sort**, and **Array.reverse** functions are not allowed, as they may change the array.|
28| itemGenerator | (item: Object, index: number) => void   | Yes  | Component generator.<br>- It generates a component for each data item in an array. <br>- **item**: data item in the **arr** array.<br>- (Optional) **index**: index of the data item in the **arr** array.<br>**NOTE**<br>- The type of the created component must be the one allowed inside the parent container component of **ForEach**. For example, a **ListItem** component is allowed only when the parent container component of **ForEach** is **List**.|
29| keyGenerator  | (item: Object, index: number) => string | No  | Key generator.<br>- It generates a unique and persistent key for each array item of the data source **arr**. The return value is the key generation rule you customize.<br>- **item**: data item in the **arr** array.<br>- (Optional) **index**: index of the data item in the **arr** array.<br>**NOTE**<br>- If this function is not specified, the default key generator of the framework is used: **(item: T, index: number) => { return index + '__' + JSON.stringify(item); }**.<br>- The key generator should not change any component state.|
30
31> **NOTE**
32>
33> - The **itemGenerator** function can contain an **if/else** statement, and an **if/else** statement can contain **ForEach**.
34> - On initial rendering, **ForEach** loads all data of the data source, creates a component for each data item, and mounts the created components to the render tree. If the data source contains a large number of items or performance is a critical concern, you are advised to use **LazyForEach**.
35
36## Properties
37
38Inherited from [DynamicNode](#dynamicnode12).
39
40## DynamicNode<sup>12+</sup>
41
42Defines a node.
43
44**Atomic service API**: This API can be used in atomic services since API version 12.
45
46**System capability**: SystemCapability.ArkUI.ArkUI.Full
47
48### onMove<sup>12+</sup>
49
50onMove(handler: Optional\<OnMoveHandler\>): T;
51
52Invoked when data is moved during drag and drop sorting. This callback is only applicable in a **List** component where each **ForEach** iteration generates a **ListItem** component.
53
54**Atomic service API**: This API can be used in atomic services since API version 12.
55
56**System capability**: SystemCapability.ArkUI.ArkUI.Full
57
58**Parameters**
59
60| Name| Type     | Mandatory| Description      |
61| ------ | --------- | ---- | ---------- |
62| handler  | Optional\<OnMoveHandler\> | Yes  | Drag operation.|
63
64## OnMoveHandler
65
66type OnMoveHandler = (from: number, to: number) => void;
67
68Defines the callback triggered when data is moved during drag and drop sorting.
69
70**Atomic service API**: This API can be used in atomic services since API version 12.
71
72**System capability**: SystemCapability.ArkUI.ArkUI.Full
73
74**Parameters**
75
76| Name| Type     | Mandatory| Description      |
77| ------ | --------- | ---- | ---------- |
78| from  | number | Yes  | Start index of the data before movement.|
79| to  | number | Yes  | Target index of the data after movement.|
80
81## Example
82
83This example demonstrates how to use **onMove** for drag and drop with **ForEach** in a **List** component.
84
85```ts
86@Entry
87@Component
88struct ForEachSort {
89  @State arr: Array<string> = [];
90
91  build() {
92    Row() {
93      List() {
94        ForEach(this.arr, (item: string) => {
95          ListItem() {
96            Text(item.toString())
97              .fontSize(16)
98              .textAlign(TextAlign.Center)
99              .size({height: 100, width: "100%"})
100          }.margin(10)
101          .borderRadius(10)
102          .backgroundColor("#FFFFFFFF")
103        }, (item: string) => item)
104          .onMove((from:number, to:number) => {
105            let tmp = this.arr.splice(from, 1);
106            this.arr.splice(to, 0, tmp[0]);
107          })
108      }
109      .width('100%')
110      .height('100%')
111      .backgroundColor("#FFDCDCDC")
112    }
113  }
114  aboutToAppear(): void {
115    for (let i = 0; i < 100; i++) {
116      this.arr.push(i.toString());
117    }
118  }
119}
120```
121
122