Custom Native React Native UI Component which implements text styles

Viewed 363

I'm working on a custom native RN UI component in Android based on these docs: https://reactnative.dev/docs/native-components-android

The component extends TextView in Android and in order to expose some of that functionality in Javascript (e.g. text selection, simple HTML styling).

The issue I'm facing is that I can't seem to get text styling to work properly. Let's say my component is called CustomTextView

In React Native, I would expect that I could do:

<CustomTextView style={{color: 'red'}} text="blah"/>

This will display the text blah in black, not red. How can I inherit from React Native's text styles in Android? Other styling rules (e.g. width, height) work properly.

Below is my implementation of CustomTextView in Java

CustomTextViewManager.java

public class CustomTextViewManager extends SimpleViewManager<TextView> {
    public static final String REACT_CLASS = "RCTCustomTextView";
    @Override
    public String getName() { return REACT_CLASS; }

    @Override
    public TextView createViewInstance(ThemedReactContext context){
        TextView view = new TextView(context);
        view.setTextIsSelectable(true);
        return view;
    }

    @ReactProp(name = "text")
    public void setText(TextView view, String text) {
        Spanned spanned;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            spanned = Html.fromHtml(text, Html.FROM_HTML_MODE_COMPACT);
        } else {
            spanned = Html.fromHtml(text);
        }
        view.setText(spanned);
    }
}

Here is a link to a repo reproducing the issue: https://github.com/nsantacruz/CustomTextViewTest

2 Answers

I did not found any docs, but for me adding of flex: 1 to styles helped.

Resulting code should be like:

<CustomTextView
  style={{
    color: 'red',
    flex: 1,
  }}
  text="blah"
/>

create a react prop in your view manager

@ReactProp(name = "textColor")
  fun setTextColor(view: View, color: String) {
    textView.setTextColor(Color.parseColor(color))
  }
Related