How to put array on WritableMap object in ReactNative bridge

4.5k Views Asked by At

To communicate with Android to ReactNative I use RCTEventEmitter. Using this I need parse array to RN side and this array should set on WritableMap object. On WritableMap object can put Array as shown below,

void putArray(@NonNull String key, @Nullable ReadableArray value);

How to create and add data into ReadableArray ?

2

There are 2 best solutions below

2
Fabio Campos On

I think you're looking for the WritableArray. You can create one like this:

// Initialize an empty array
WritableArray array = new WritableNativeArray();

// Add items to array using its push methods, for example
array.pushString("test");
0
user56reinstatemonica8 On

Arguments from React Native Bridge has a helper method Arguments.fromList(list) that returns a WritableArray, which is a subclass of ReadableArray, so satisfies the condition and is ready to pass to putArray.


For example, to take a list and push it to a JS event as an array property:

Kotlin:

import com.facebook.react.bridge.Arguments
// ...

val params = Arguments.createMap().apply {
   putArray("data", Arguments.fromList(someList))
   // ...put more params
}

Java:

import com.facebook.react.bridge.Arguments;
// ...

WriteableArray array = Arguments.fromList(someList);
WritableMap params = Arguments.createMap();
params.putArray(array);
// ...put more params

Pass these to .emit("SomeEvent", params) and JS should receive { data: [...someList] }.


There's also Arguments.makeNativeArray(list), which has an almost identical API and implementation to .fromList - both create a WritableArray by iterating a list arg, pushing each item by type. The only differences I can see are:

  • .fromList explicitly handles nested arrays
  • .makeNativeArray explicitly handles null (returning an empty array)