DEV Community

Marxu
Marxu

Posted on

๐ŸŒŸ ArkTS Demystified: Build Modern UI with HarmonyOS Declarative Syntax(HarmonyOS 5.0.0 or high)

๐ŸŒŸ ArkTS Demystified: Build Modern UI with HarmonyOS Declarative Syntax

ArkTS is the beating heart of HarmonyOS 5.0+. It's concise, reactive, and tailor-made for multi-device development. Letโ€™s build a modern UI and understand how it works.


๐Ÿ“– What is ArkTS?

ArkTS is a TypeScript-inspired declarative UI language in HarmonyOS. Think of it as the best of SwiftUI + React Native โ€” but for distributed apps.


๐ŸŽฏ Our Goal

Weโ€™ll build a reusable Counter component with:

  • State management
  • Event handling
  • Component composition

๐Ÿงฑ Step 1: Create a Counter Component

File: entry/src/main/ets/components/Counter.ets

@Component export struct Counter { @State count: number = 0; build() { Column() { Text(`Count: ${this.count}`) .fontSize(24) .margin(12) Row() { Button('-') .onClick(() => this.count--) .margin(8) Button('+') .onClick(() => this.count++) .margin(8) } } .alignItems(HorizontalAlign.Center) .justifyContent(FlexAlign.Center) .width('100%') .height('100%') } } 
Enter fullscreen mode Exit fullscreen mode

๐Ÿ› ๏ธ Step 2: Use the Counter in Index Page

File: pages/Index.ets

import { Counter } from '../components/Counter'; @Component struct IndexPage { build() { Column() { Text('Welcome to ArkTS Counter') .fontSize(28) .fontWeight(FontWeight.Bold) .margin(16) Counter() } .width('100%') .height('100%') } } 
Enter fullscreen mode Exit fullscreen mode

๐ŸŽฎ Run Result

  • Shows title + counter value
  • Click + / - to increment/decrement
  • Full reactive re-rendering on state update

๐Ÿ–ผ๏ธ UI Preview:

[ Welcome to ArkTS Counter ] [ Count: 0 ] [ [-] [+] ] 
Enter fullscreen mode Exit fullscreen mode

โš ๏ธ Easy Mistakes to Avoid

Mistake Cause Fix
count doesn't update UI Forgot @State Add @State before the variable
Buttons unresponsive Wrong method syntax Use arrow functions: () => this.count++
Error: โ€˜Counter not foundโ€™ Wrong path or forgot export Ensure export is used + import path correct
Layout not centered No .alignItems() or .justifyContent() Add them to the layout container

๐Ÿ“Œ Summary

You now know how to:

  • Define reusable UI components
  • Use ArkTS stateful logic
  • Build layouts using Column, Row, Text, and Button

๐Ÿ”ฎ Coming Next...

In the next post, weโ€™ll explore distributed app development with HarmonyOS โ€” build once, run on multiple devices!

๐Ÿ‘‰ Subscribe for more hands-on HarmonyOS guides. Letโ€™s master ArkTS together.

Top comments (0)