Featured image of post Handling Dynamic Text Updates in HarmonyOS ArkUI ForEach

Handling Dynamic Text Updates in HarmonyOS ArkUI ForEach

Learn how to manage dynamic array updates, split text blocks, use splice(), and solve stale TextArea UI issues in HarmonyOS ArkUI ForEach.

Handling Dynamic Text Updates in HarmonyOS ArkUI ForEach

When developing a rich-text editor or an image-and-text editing interface in HarmonyOS, managing dynamic content can become challenging.

A common implementation is to maintain an array of content blocks, where each element represents either a text paragraph or an image.

For example:

  • Users can edit individual text blocks.
  • Images can be inserted between paragraphs.
  • Text blocks can be split when an image is inserted.
  • Content blocks can be deleted, replaced, or reordered.

However, developers may encounter a frustrating issue: the underlying array has been updated, but the UI does not reflect the changes.

This article explores how to manage these operations using ArkTS arrays, splice(), ForEach, and ArkUI state management.

1. Managing Two Independent Arrays

In some editing scenarios, it is useful to maintain two arrays:

  • originalList: Stores the original content.
  • editingList: Stores the content currently being edited.

Initially, both arrays contain the same data. However, modifications should only affect the editing copy.

A simple implementation might look like this:

@State originalList: ContentBlock[] = [];
@State editingList: ContentBlock[] = [];

When initializing the editing array, be careful with JavaScript’s shallow-copy behavior.

For example:

this.editingList = [...this.originalList];

This creates a new array, but the objects inside both arrays still reference the same instances.

Consequently, modifying an object in editingList may also affect originalList.

For independent editing, create new objects:

this.editingList = this.originalList.map(item => ({
  ...item
}));

This approach is sufficient when the objects contain only primitive properties.

If the objects contain nested arrays or nested objects, a deeper copy is necessary.

The key principle is to separate the original data from the editing data so that changes do not unintentionally affect the original content.

2. Understanding Array.splice()

The splice() method is particularly useful when dynamically modifying content blocks.

Its syntax is:

array.splice(start, deleteCount, item1, item2, ...);

Parameters:

  • start: The index where the operation begins.
  • deleteCount: The number of existing elements to remove.
  • item1, item2, ...: New elements to insert.

2.1 Inserting Elements

To insert two elements immediately after an existing element:

list.splice(
  targetIndex + 1,
  0,
  img1,
  text2
);

Setting deleteCount to 0 means no existing elements are removed.

For example:

let list = ['Text A', 'Text B', 'Text C'];

list.splice(1, 0, 'Image', 'Text D');

The resulting array becomes:

[
  'Text A',
  'Image',
  'Text D',
  'Text B',
  'Text C'
]

Existing elements are automatically shifted to make room for the inserted elements.

2.2 Replacing an Element

The same method can also replace existing elements.

list.splice(targetIndex, 1, newItem);

This removes one element at the specified index and inserts a replacement.

You can also replace one element with multiple elements.

For example, when splitting a text block into two paragraphs with an image between them:

list.splice(
  targetIndex,
  1,
  text1,
  img1,
  text2
);

This is especially useful for implementing rich-text editing functionality.

3. Splitting a Text Block When Inserting an Image

Consider a scenario where a user is editing a paragraph and decides to insert an image at the current cursor position.

Suppose the original text is:

Hello HarmonyOS, welcome to rich-text editing!

If the user inserts an image somewhere in the middle, the original text needs to be divided into two parts.

The resulting content structure should look like this:

[ { type: 'text', content: 'Hello HarmonyOS,' }, { type: 'image', content: 'image-url' }, { type: 'text', content: ' welcome to rich-text editing!' } ]

Instead of maintaining complicated text offsets inside a single input component, each content block can be managed independently.

A simplified implementation:

interface ContentBlock {
  id: string;
  type: 'text' | 'image';
  content: string;
}

insertImageAtCursor(
  index: number,
  cursorOffset: number,
  imageUrl: string
): void {
  const oldBlock = this.editingList[index];

  if (oldBlock.type !== 'text') {
    return;
  }

  const fullText = oldBlock.content;

  const firstPart = fullText.slice(0, cursorOffset);
  const secondPart = fullText.slice(cursorOffset);

  const text1: ContentBlock = {
    id: this.generateId(),
    type: 'text',
    content: firstPart
  };

  const img1: ContentBlock = {
    id: this.generateId(),
    type: 'image',
    content: imageUrl
  };

  const text2: ContentBlock = {
    id: this.generateId(),
    type: 'text',
    content: secondPart
  };

  this.editingList.splice(
    index,
    1,
    text1,
    img1,
    text2
  );
}

The original text block is replaced with three new blocks.

This approach makes content management much easier because each text paragraph and image has its own independent identity.

In a production implementation, generateId() should return a reliably unique identifier.

Also consider preserving empty text blocks when inserting images at the beginning or end of a paragraph. This allows users to continue typing before or after an image.

4. Why Does ForEach Sometimes Fail to Update the UI?

One of the most confusing problems in ArkUI is that the data has changed, but the corresponding UI remains unchanged.

For example:

ForEach(
  this.editingList,
  (item: ContentBlock) => {
    if (item.type === 'text') {
      TextArea({
        text: item.content
      });
    } else {
      Image(item.content)
        .width('100%');
    }
  },
  (item: ContentBlock) => item.id
);

There are several possible reasons.

4.1 The Array Is Not Properly Observed

If the array is declared as an ordinary class property rather than a reactive state variable, ArkUI may not know that its contents have changed.

For example:

editingList: ContentBlock[] = [];

For a state-managed V1 component, a typical declaration is:

@State editingList: ContentBlock[] = [];

This allows ArkUI to observe supported changes to the state.

However, array observation and object-property observation are not exactly the same thing.

Changing an object’s internal property does not necessarily trigger the expected UI update:

this.editingList[0].content = 'Updated content';

If the element is a plain object, its nested property changes may not be observed as expected.

Possible solutions include:

  • Replacing the entire array.
  • Replacing the modified element with a new object.
  • Using the appropriate observable object model, such as @Observed and @ObjectLink in state management V1.

For example:

this.editingList[index] = {
  ...this.editingList[index],
  content: 'Updated content'
};

For more complex editing interfaces, using observable model objects and dedicated child components can provide more predictable updates.

4.2 Incorrect ForEach Key Generation

The third parameter of ForEach is the key generator.

It tells ArkUI how to identify individual list elements.

A common implementation is:

ForEach(
  this.editingList,
  (item: ContentBlock) => {
    // UI rendering
  },
  (item: ContentBlock) => item.id
);

Every item should have a unique and stable ID.

Avoid using the array index as the key:

(item, index) => index.toString()

When elements are inserted or removed, their indexes change. This can cause existing component nodes to be reused for different data items.

It is also important not to include frequently changing content in the key:

(item) => `${item.id}_${item.content}`

Although changing the content changes the key, it can force unnecessary component recreation during normal typing, potentially causing focus and cursor problems.

Recommended approach: use a stable, unique ID for each content block.

The key should represent the identity of the content block, not its current content.

5. Keeping TextArea and Data Synchronized

Even when the array updates correctly, a TextArea may display outdated content if its internal state and the external data are not properly synchronized.

This is particularly important in rich-text editors because users frequently modify text.

A basic implementation might look like this:

TextArea({
  text: item.content
})
.onChange((value: string) => {
  item.content = value;
});

This updates the data when the user types.

However, the reverse direction also matters.

If the application changes item.content programmatically, the TextArea must receive the updated value through the appropriate reactive binding mechanism.

For HarmonyOS ArkUI, consider the following approaches.

Approach A: Replace the Data Object

When splitting a text block, create new objects instead of modifying the original object and reusing its identity.

this.editingList.splice(
  index,
  1,
  text1,
  img1,
  text2
);

Combined with stable unique IDs, this allows ForEach to distinguish the newly created content blocks from the old one.

For state management V1, another approach is to make each content block observable and render it through a child component.

For example:

@Observed
class ContentBlock {
  id: string;
  type: string;
  content: string;

  constructor(
    id: string,
    type: string,
    content: string
  ) {
    this.id = id;
    this.type = type;
    this.content = content;
  }
}

A child component can receive the block through @ObjectLink:

@Component
struct ContentItem {
  @ObjectLink block: ContentBlock;

  build() {
    if (this.block.type === 'text') {
      TextArea({
        text: this.block.content
      })
      .onChange((value: string) => {
        this.block.content = value;
      });
    } else {
      Image(this.block.content)
        .width('100%');
    }
  }
}

The parent component can then render the blocks:

ForEach(
  this.editingList,
  (item: ContentBlock) => {
    ContentItem({
      block: item
    });
  },
  (item: ContentBlock) => item.id
);

With this structure, changes to observable object properties can be propagated to the corresponding child component.

Note: This example uses the V1 state management model. HarmonyOS also provides the V2 state management system, which uses different decorators and observation rules. Choose the implementation according to the project’s API version and state management model.

6. Common Operations in a Rich-Text Editor

Once content is represented as independent blocks, several editing operations become straightforward.

OperationArray operation
Insert an image into textsplice(index, 1, text1, image, text2)
Append a new paragraphsplice(list.length, 0, newItem)
Delete an imagesplice(index, 1)
Replace a content blocksplice(index, 1, newItem)
Replace multiple blockssplice(index, count, ...newItems)
Move a blockRemove it and insert it at another index

For example, deleting an image and merging the surrounding text blocks:

const previous = this.editingList[index - 1];
const next = this.editingList[index + 1];

const mergedText: ContentBlock = {
  id: this.generateId(),
  type: 'text',
  content: previous.content + next.content
};

this.editingList.splice(
  index - 1,
  3,
  mergedText
);

This example assumes that the target image is surrounded by two text blocks. In a real editor, you should also validate the indexes and block types before performing the operation.

7. Practical Considerations

When implementing a dynamic content editor in HarmonyOS, keep the following points in mind:

  1. Use independent data objects: Avoid accidental reference sharing between the original array and the editing array.
  2. Use splice() for structural changes: It is convenient for inserting, deleting, replacing, and splitting content blocks.
  3. Assign unique IDs: Every content block should have a stable identifier.
  4. Use stable ForEach keys: Prefer item.id instead of the array index or frequently changing content.
  5. Understand state observation: @State does not automatically make every nested object property observable.
  6. Synchronize TextArea properly: Make sure both user input and programmatic changes are reflected in the UI.
  7. Handle focus and cursor position: After splitting a text block, consider moving focus to the newly created text block so users can continue typing naturally.

Conclusion

When building dynamic editing interfaces in HarmonyOS ArkUI, the most important thing is to separate data management from UI rendering.

Using an array of independent content blocks makes rich-text editing much easier to maintain.

The splice() method provides a convenient way to perform structural changes, while ForEach handles rendering each block.

However, correct array operations alone do not guarantee that the UI will update.

You also need to understand ArkUI’s state observation mechanism, component identity, and TextArea synchronization.

Once these concepts are handled correctly, operations such as inserting images, splitting paragraphs, deleting blocks, and merging text become much more predictable and maintainable.

comments powered by Disqus