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 create 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 using methods such as [if/else](../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../quick-start/arkts-rendering-control-foreach.md), and [LazyForEach](../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 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 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 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 allow a single grid cell in a grid to span multiple rows or columns, passing appropriate [GridLayoutOptions](../reference/apis-arkui/arkui-ts/ts-container-grid.md#gridlayoutoptions10) when creating the grid. Use **irregularIndexes** and **onGetIrregularSizeByIndex** for grids with only **rowsTemplate** or **columnsTemplate**, and **onGetRectByIndex** for grids with both. 74 75**Figure 4** Uneven grid layout 76 77 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 84 85In the grid, use the **onGetRectByIndex** callback to return the array [rowStart, columnStart, rowSpan, columnSpan] to achieve a layout that spans rows and columns, wherein **rowStart** and **rowEnd** indicate the start and end row numbers of the current element, and **columnStart** and **columnEnd** indicate the start and end column numbers of the current element. 86 87To make the **0** key span across the first and second columns, and the **=** key span across the fifth and sixth rows, set **onGetRectByIndex** for **0** and **=** as follows: for **0**, set **rowStart** and **columnStart** at **5** and **0**, and **rowSpan** and **columnSpan** at **1** and **2**; for **=**, set **rowStart** and **columnStart** at **4** and **3**, and **rowSpan** and **columnSpan** at **2** and **1**. 88 89 90```ts 91layoutOptions: GridLayoutOptions = { 92 regularSize: [1, 1], 93 onGetRectByIndex: (index: number) => { 94 if (index = = key1) { // key1 is the index of the 0 key. 95 return [5, 0, 1, 2] 96 } else if (index == key2) { // key2 is the index of the = key. 97 return [4, 3, 2, 1] 98 } 99 // ... 100 // Here, you need to return the positions of other items based on the specific layout. 101 } 102} 103 104Grid(undefined, this.layoutOptions) { 105 // ... 106} 107.columnsTemplate('1fr 1fr 1fr 1fr') 108.rowsTemplate('2fr 1fr 1fr 1fr 1fr 1fr') 109``` 110 111 112### Setting the Main Axis Direction 113 114When 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. 115 116**Figure 6** Main axis direction 117 118 119 120When **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. 121 122 123```ts 124Grid() { 125 ... 126} 127.maxCount(3) 128.layoutDirection(GridDirection.Row) 129``` 130 131>**NOTE** 132> 133>- 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**. 134>- 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. 135>- 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. 136 137 138## Displaying Data in a Grid Layout 139 140The grid layout organizes its internal elements in two-dimensional layout mode, as shown in the following figure. 141 142**Figure 7** General office services 143 144 145 146The **Grid** component can display a group of **GridItem** child components in two-dimensional layout mode. 147 148 149```ts 150Grid() { 151 GridItem() { 152 Text('Conference') 153 ... 154 } 155 156 GridItem() { 157 Text('Sign-in') 158 ... 159 } 160 161 GridItem() { 162 Text('Vote') 163 ... 164 } 165 166 GridItem() { 167 Text('Print') 168 ... 169 } 170} 171.rowsTemplate('1fr 1fr') 172.columnsTemplate('1fr 1fr') 173``` 174 175For multiple **GridItem** components with similar content structures, you are advised to nest them in **ForEach** statements to reduce repeated code. 176 177 178```ts 179@Entry 180@Component 181struct OfficeService { 182 @State services: Array<string> = ['Conference', 'Vote','Sign-in', 'Print'] 183 184 build() { 185 Column() { 186 Grid() { 187 ForEach(this.services, (service:string) => { 188 GridItem() { 189 Text(service) 190 } 191 }, (service:string):string => service) 192 } 193 .rowsTemplate(('1fr 1fr') as string) 194 .columnsTemplate(('1fr 1fr') as string) 195 } 196 } 197} 198``` 199 200 201## Setting the Gap Between Rows and Columns 202 203The horizontal spacing between two grid cells is called row spacing, and the vertical spacing is called column spacing, as shown in the following figure. 204 205**Figure 8** Row spacing and column spacing 206 207 208 209You 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. 210 211 212```ts 213Grid() { 214 ... 215} 216.columnsGap(10) 217.rowsGap(15) 218``` 219 220 221## Building a Scrollable Grid Layout 222 223The 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. 224 225**Figure 9** Horizontal scrollable grid layout 226 227 228 229If **columnsTemplate** is set, the grid scrolls vertically. If **rowsTemplate** is set, the grid scrolls horizontally. 230 231In 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. 232 233 234```ts 235@Entry 236@Component 237struct Shopping { 238 @State services: Array<string> = ['Live', 'Premium'] 239 240 build() { 241 Column({ space: 5 }) { 242 Grid() { 243 ForEach(this.services, (service: string, index) => { 244 GridItem() { 245 } 246 .width('25%') 247 }, (service:string):string => service) 248 } 249 .rowsTemplate('1fr 1fr') // Set only the rowsTemplate attribute. When the content exceeds the display area of the grid, the grid can be scrolled horizontally. 250 .rowsGap(15) 251 } 252 } 253} 254``` 255 256 257## Controlling the Scrolling Position 258 259Similar 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. 260 261**Figure 10** Page turning in the calendar application 262 263 264 265When 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. 266 267 268```ts 269private scroller: Scroller = new Scroller() 270``` 271 272On 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. 273 274 275```ts 276Column({ space: 5 }) { 277 Grid(this.scroller) { 278 } 279 .columnsTemplate('1fr 1fr 1fr 1fr 1fr 1fr 1fr') 280 281 Row({space: 20}) { 282 Button('Previous') 283 .onClick(() => { 284 this.scroller.scrollPage({ 285 next: false 286 }) 287 }) 288 289 Button('Next') 290 .onClick(() => { 291 this.scroller.scrollPage({ 292 next: true 293 }) 294 }) 295 } 296} 297``` 298 299 300## Performance Optimization 301 302Just 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. 303 304For details about the implementation, see the example in [LazyForEach: Lazy Data Loading](../quick-start/arkts-rendering-control-lazyforeach.md). 305 306When 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**. 307 308 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. 309 310```ts 311Grid() { 312 LazyForEach(this.dataSource, () => { 313 GridItem() { 314 } 315 }) 316} 317.cachedCount(3) 318``` 319 320>**NOTE** 321> 322>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. 323 324