• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Creating a Grid (Grid/GridItem)
2
3
4## Overview
5
6The grid layout consists of cells formed by rows and columns. You can specify the cells where items are located to form various layouts. The grid layout excels at dividing a page into regions and defining the proportion of child components. It is a key adaptive layout and applies to scenarios such as photo gallery, calendar, and calculator.
7
8ArkUI provides the [\<Grid>](../reference/apis-arkui/arkui-ts/ts-container-grid.md) and [\<GridItem>](../reference/apis-arkui/arkui-ts/ts-container-griditem.md) components for building grid layouts. **\<Grid>** is a container for defining the grid layout, while **\<GridItem>** is a child component in the container. The **\<Grid>** component allows creation of child components with conditional rendering, rendering of repeated content, and [lazy data loading](../quick-start/arkts-rendering-control-lazyforeach.md).
9
10
11## Layout and Constraints
12
13Each item in the **\<Grid>** container corresponds to a **\<GridItem>** component, as shown below.
14
15**Figure 1** Relationship between \<Grid> and \<GridItem> components
16
17![en-us_image_0000001511900472](figures/en-us_image_0000001511900472.png)
18
19>**NOTE**
20>
21>The **\<Grid>** component accepts only **\<GridItem>** as its child.
22
23The grid layout is a two-dimensional layout. The **\<Grid>** component allows you to define the number of rows and columns, proportion of each row and column, number of rows or columns that child components span, and the horizontal and vertical alignment. When it has its size changed, its child components and spacing are adjusted proportionally. By leveraging these layout capabilities, you can build grid layouts of different styles, as shown below.
24
25**Figure 2** Grid layout
26
27![en-us_image_0000001562700473](figures/en-us_image_0000001562700473.png)
28
29The size of the **\<Grid>** component follows its width and height settings (if configured) or adapts to the size of its parent component.
30
31Depending on the settings of the quantity and proportion of rows and columns, the **\<Grid>** component behaves as follows:
32
33- If both the quantity and proportion are set for rows or columns, the **\<Grid>** component displays elements only in the set number of rows or columns, and it cannot be scrolled. (This layout mode is recommended.)
34
35- If only the quantity or proportion is set for rows or columns, the **\<Grid>** component lays out elements in the specified direction, and it can be scrolled to display excess elements.
36
37- If neither the quantity nor the proportion is set for rows or columns, the **\<Grid>** component lays out elements in the layout direction. The number of rows and columns is determined by the layout direction and the width and height of the grid. Elements that exceed the range of rows and columns are not displayed, and the **\<Grid>** component cannot be scrolled.
38
39
40## Setting the Arrangement Mode
41
42
43### Setting the Number and Proportion of Rows and Columns
44
45You can set the number and proportion of rows and columns to determine the overall arrangement mode of the grid layout. To do so, use the **rowsTemplate** and **columnsTemplate** attributes of the **\<Grid>** component.
46
47The values of **rowsTemplate** and **columnsTemplate** are a string consisting of 'number+fr' segments, separated by spaces. Wherein **fr** indicates the number of rows or columns in the grid layout, and the number in front of **fr** is used to calculate the proportion of the row or column in the grid width, thereby determining the width of the row or column.
48
49**Figure 3** Example of the proportion of rows and columns
50
51![en-us_image_0000001562820833](figures/en-us_image_0000001562820833.png)
52
53The preceding figure shows a grid layout with three rows and three columns. The grid layout is divided into three parts in the vertical direction with each row taking up 1/3, and four parts in the horizontal direction with the first column taking up 1/4, the second column 2/4, and the third column 1/4.
54
55This layout can be implemented by setting **rowsTemplate** to **'1fr 1fr 1fr'** and **columnsTemplate** to **'1fr 2fr 1fr'**.
56
57
58```ts
59Grid() {
60  ...
61}
62.rowsTemplate('1fr 1fr 1fr')
63.columnsTemplate('1fr 2fr 1fr')
64```
65
66>**NOTE**
67>
68>When **rowsTemplate** or **columnsTemplate** is set for the **\<Grid>** component, its **layoutDirection**, **maxCount**, **minCount**, and **cellLength** attributes do not take effect. For details about the attributes, see [Grid Attributes](../reference/apis-arkui/arkui-ts/ts-container-grid.md#attributes).
69
70
71### Setting the Number of Rows and Columns Occupied by a Child Component
72
73In real-world applications, an uneven grid layout, where grid cells span a varying number of cells and rows, is as common as its even counterpart. To implement an uneven grid layout, as shown below, you can set **rowStart**, **rowEnd**, **columnStart**, and **columnEnd** of **\<GridItem>**. The valid value range of **rowStart** and **rowEnd** is 0 to the total number of rows minus 1. The valid value range of **columnStart** and **columnEnd** is 0 to the total number of columns minus 1. For details, see [GridItem](../reference/apis-arkui/arkui-ts/ts-container-griditem.md).
74
75**Figure 4** Uneven grid layout
76
77![en-us_image_0000001511900480](figures/en-us_image_0000001511900480.png)
78
79A common application with an uneven grid layout is the calculator. As shown in the following figure, the **0** key spans the first and second columns, and the **=** key spans the fifth and sixth rows. For a grid layout created using the **\<Grid>** component, the row and column numbers start from 0 and increase incrementally.
80
81**Figure 5** Calculator
82
83![en-us_image_0000001511421292](figures/en-us_image_0000001511421292.png)
84
85For a single grid cell, the **rowStart** and **rowEnd** attributes indicate the start and end row numbers of the current element, and the **columnStart** and **columnEnd** attributes indicate the start and end column numbers of the current element.
86
87Therefore, for the **0** key to span the first and second columns, just set the **\<GridItem>** component of the key as follows: **columnStart** to **1**, **columnEnd** to **2**, **rowStart** and **rowEnd** to **5**.
88
89
90```ts
91GridItem() {
92  Text(key)
93    ...
94}
95.columnStart(0)
96.columnEnd(1)
97.rowStart(5)
98.rowEnd(5)
99```
100
101For the **=** key to span the fifth and sixth rows, just set the **\<GridItem>** component of the key as follows: **rowStart** to **4**, **rowEnd** to **5**, **columnStart** and **columnStart** to **4**.
102
103
104```ts
105GridItem() {
106  Text(key)
107    ...
108}
109.rowStart(4)
110.rowEnd(5)
111.columnStart(4)
112.columnEnd(4)
113```
114
115
116### Setting the Main Axis Direction
117
118When neither the number nor proportion is set for rows and columns in a grid layout, you can use the **layoutDirection** attribute to set the main axis direction and thereby specify the arrangement mode of child components. In addition, you can use the **minCount** and **maxCount** attributes to restrict the number of grid cells along the main axis.
119
120**Figure 6** Main axis direction
121
122![en-us_image_0000001562700469](figures/en-us_image_0000001562700469.png)
123
124When **layoutDirection** is set to **Row**, child components are arranged from left to right. When a row is full, a new row is added. When **layoutDirection** is set to **Column**, child components are arranged from top to bottom. When a column is full, a new column is added. In this example, the **maxCount** attribute is set to **3**, indicating that the maximum number of grid cells displayed along the main axis is 3.
125
126
127```ts
128Grid() {
129  ...
130}
131.maxCount(3)
132.layoutDirection(GridDirection.Row)
133```
134
135>**NOTE**
136>
137>- The **layoutDirection** attribute takes effect only when **rowsTemplate** and **columnsTemplate** are not set. In this case, child components are arranged in the direction set by **layoutDirection**.
138>- When only **rowsTemplate** is set, the main axis of the grid runs in the horizontal direction, and the cross axis runs in the vertical direction.
139>- When only **columnsTemplate** is set, the main axis of the grid runs in the vertical direction, and the cross axis runs in the horizontal direction.
140
141
142## Displaying Data in a Grid Layout
143
144The grid layout organizes its internal elements in two-dimensional layout mode, as shown in the following figure.
145
146**Figure 7** General office services
147
148![en-us_image_0000001563060729](figures/en-us_image_0000001563060729.png)
149
150The **\<Grid>** component can display a group of **\<GridItem>** child components in two-dimensional layout mode.
151
152
153```ts
154Grid() {
155  GridItem() {
156    Text('Conference')
157      ...
158  }
159
160  GridItem() {
161    Text('Sign-in')
162      ...
163  }
164
165  GridItem() {
166    Text ('Vote')
167      ...
168  }
169
170  GridItem() {
171    Text ('Print')
172      ...
173  }
174}
175.rowsTemplate('1fr 1fr')
176.columnsTemplate('1fr 1fr')
177```
178
179For multiple **\<GridItem>** components with similar content structures, you are advised to nest them in **ForEach** statements to reduce repeated code.
180
181
182```ts
183@Entry
184@Component
185struct OfficeService {
186  @State services: Array<string> = ['Conference', 'Vote','Sign-in', 'Print']
187
188  build() {
189    Column() {
190      Grid() {
191        ForEach(this.services, (service:string) => {
192          GridItem() {
193            Text(service)
194          }
195        }, (service:string):string => service)
196      }
197      .rowsTemplate(('1fr 1fr') as string)
198      .columnsTemplate(('1fr 1fr') as string)
199    }
200  }
201}
202```
203
204
205## Setting the Gap Between Rows and Columns
206
207The horizontal spacing between two grid cells is called row spacing, and the vertical spacing is called column spacing, as shown in the following figure.
208
209**Figure 8** Row spacing and column spacing
210
211![en-us_image_0000001511580908](figures/en-us_image_0000001511580908.png)
212
213You can use **rowsGap** and **columnsGap** to set the row spacing and column spacing of the grid layout. In the calculator shown in Figure 5, the row spacing is 15 vp, and the column spacing is 10vp.
214
215
216```ts
217Grid() {
218  ...
219}
220.columnsGap(10)
221.rowsGap(15)
222```
223
224
225## Building a Scrollable Grid Layout
226
227The scrollable grid layout is often used on the file list, product list, video list, and similar pages, as shown in the following figure. When only the number or proportion is set for rows and columns, that is, only the **rowsTemplate** or **columnsTemplate** attribute is set, the elements in the grid are arranged in the configured direction. When the content goes beyond the display area, the grid can be scrolled.
228
229**Figure 9** Horizontal scrollable grid layout
230
231![en-us_image_0000001511740512](figures/en-us_image_0000001511740512.gif)
232
233If **columnsTemplate** is set, the grid scrolls vertically. If **rowsTemplate** is set, the grid scrolls horizontally.
234
235In the horizontal scrollable grid layout shown in the preceding figure, **rowsTemplate** is set but **columnsTemplate** is not. When the content exceeds the width of the grid, the grid can scroll horizontally to display the content outside of the display area.
236
237
238```ts
239@Entry
240@Component
241struct Shopping {
242  @State services: Array<string> = ['Live', 'Premium']
243
244  build() {
245    Column({ space: 5 }) {
246      Grid() {
247        ForEach(this.services, (service: string, index) => {
248          GridItem() {
249          }
250          .width('25%')
251        }, (service:string):string => service)
252      }
253      .rowsTemplate('1fr 1fr') // Set only the rowsTemplate attribute. When the content exceeds the display area of the grid, the grid can be scrolled horizontally.
254      .rowsGap(15)
255    }
256  }
257}
258```
259
260
261## Controlling the Scrolling Position
262
263Similar to the Back to top button in a list layout, the feature of controlling the scrolling position is commonly used in the grid layout, for example, page turning in the calendar application, as shown below.
264
265**Figure 10** Page turning in the calendar application
266
267![en-us_image_0000001562940549](figures/en-us_image_0000001562940549.gif)
268
269When the **\<Grid>** component is initialized, it can be bound to a [Scroller](../reference/apis-arkui/arkui-ts/ts-container-scroll.md#scroller) object for scrolling control. In this example, the [scrollPage](../reference/apis-arkui/arkui-ts/ts-container-scroll.md#scrollpage9) API of the **Scroller** object is used to turn pages.
270
271
272```ts
273private scroller: Scroller = new Scroller()
274```
275
276On the calendar page, when a user clicks the **Next** button, the application responds to the click event by setting the **next** parameter in the **scrollPage** API to **true** to scroll to the next page.
277
278
279```ts
280Column({ space: 5 }) {
281  Grid(this.scroller) {
282  }
283  .columnsTemplate('1fr 1fr 1fr 1fr 1fr 1fr 1fr')
284
285  Row({space: 20}) {
286    Button ('Previous')
287      .onClick(() => {
288        this.scroller.scrollPage({
289          next: false
290        })
291      })
292
293    Button ('Next')
294      .onClick(() => {
295        this.scroller.scrollPage({
296          next: true
297        })
298      })
299  }
300}
301```
302
303
304## Performance Optimization
305
306Just as [LazyForEach](../quick-start/arkts-rendering-control-lazyforeach.md) is recommended for [handling a long list](arkts-layout-development-create-list.md#handling-a-long-list), it is also recommended for a scrolling grid layout when a large number of grid items is involved.
307
308For details about the implementation, see the example in [LazyForEach: Lazy Data Loading](../quick-start/arkts-rendering-control-lazyforeach.md).
309
310When the grid is rendered in lazy loading mode, to improve the grid scrolling experience and minimize white blocks during grid scrolling, you can use the **cachedCount** parameter of the **\<Grid>** component. This parameter sets the number of grid items preloaded outside of the screen and is valid only in **LazyForEach**.
311
312  Specifically, the number of the grid items to cache before and after the currently displayed one equals the value of **cachedCount** multiplied by the number of columns. Grid items that exceed the display and cache range are released.
313
314```ts
315Grid() {
316  LazyForEach(this.dataSource, () => {
317    GridItem() {
318    }
319  })
320}
321.cachedCount(3)
322```
323
324>**NOTE**
325>
326>A greater **cachedCount** value may result in higher CPU and memory overhead of the UI. Adjust the value by taking into account both the comprehensive performance and user experience.
327
328