Home > Enterprise >  How to pass a color prop in React Native
How to pass a color prop in React Native

Time:09-30

I would like to pass color prop to native sdk UI. I was trying to pass it in style prop but it did not help. Does anyone know, how to parse color on native side ?

CodePudding user response:

that's strange that you have a problem with passing staff through flat props and styles object as it should be handled out of the box.

Simple case

The only thing that you need to do is mark the property with color type, on IOS.

RCT_EXPORT_VIEW_PROPERTY(myMagicColorProp, UIColor)

On Android colors are just simply integers so you should just simply use Integer

@ReactProp(name = "myMagicColor")
fun setColor(view: View, color: Int?) {
    // ...
}

Complex case

If you are trying to pass color in some nested structure e.g.

<MyComponent data={{ magicColor: "red"}} />

You have to handle parsing color on your own. Thankfully facebook gave us some tools for that.

First of all, you have to normalize the color on the JS side

import { processColor } from 'react-native'


<MyComponent data={{ magicColor: processColor("red") }} />

Next on IOS you have to use RCTConvert to get UIColor

    @objc func setData(_ data: NSDictionary) {
        let color = RCTConvert.uiColor(data["magicColor"])
        /// ...
    }

On Android you don't have to do anything more than just simply use getInt

  @ReactProp(name = "data")
  fun setData(view: View, data: ReadableMap?) {
      view.setBackgroundColor(data.getInt("color"))
      /// ...
  }

  • Related