Raj Suvariya
Raj Suvariya

Reputation: 1664

How to access dimensions from android and apply it to style in react native

I am developing a hybrid app react native + Android. I want consistent font size throughout the app. So I want to access the font size declared in dimen.xml of Android, where I have created stubs for different dimensions of different devices. I can expose it via Native Modules like this

@ReactMethod
public float getFontSize(Callback callback){
    callback.invoke(mContext.getResources().getDimension(R.dimen.text_h1));
    return mContext.getResources().getDimension(R.dimen.text_h1);
}

and I can access it from react native like this

NativeModules.Utilities.getFontSize((textsize)=>console.log(textsize))

But then How can I add it to my following style?

TextStyleH1: {
    ...Platform.select({
      ios: {
        fontFamily: "PFEncoreSansPro-Book",
      },
      android: {
        fontFamily: "pfencoresanspro_book",
      },
    }),
    fontSize: 18, // I want to change to textsize returned from NativeModule
  },

Clarification

My styles are defined in styles.js which has

const styles = StyleSheet.create({
   ...
});

because I want it to be reusable as I have 14 diff styles of text and have lot of <Text /> in my components. So I want to change the fontSize inside styles.js only (if possible)

Upvotes: 2

Views: 351

Answers (1)

Val
Val

Reputation: 22817

You have to add it by appending style:

componentWillMount() {        
    NativeModules.Utilities.getFontSize((textsize)=>this.setState({textsize}));
}

render() {
    return (
        <Text style={[styles.TextStyleH1, {
            fontSize: this.state.textsize
        }]}>
            Sample Text
        </Text>
    );
}

Upvotes: 1

Related Questions