Styling Custom Components in React Native Using TypeScript

Article summary

I recently ran into an issue with providing style properties to custom React Native components written in TypeScript. When defining the type of the style property, we were using the ViewStyle and TextStyle types provided by React Native.


interface Props {
  textStyle?: TextStyle;
  viewStyle?: ViewStyle;
}

class BlogPost extends React.PureComponent<Props> {
  render() {
    return (
      <View style={this.props.viewStyle}>
        <Text style={this.props.textStyle}>Hello World</Text>
      </View>
    );
  }
}

class Example extends React.PureComponent<Props> {
  render() {
    return (
      <View>
        <BlogPost viewStyle={styles.x} textStyle={styles.y} />
      </View>
    );
  }
}

This was good enough in most cases, but soon, we ran into the issue of passing multiple styles into a component. In this case, style={[styles.x, styles.y]} would not be accepted by the TypeScript compiler.

We temporarily solved the issue by changing the style types to ViewStyle | ViewStyle[]. This solved more issues, but we quickly ran into another: passing in multiple conditional styles. For example, style={[style.x, boldText ? style.bold : undefined]} would not work.

The Solution

After digging into the React Native Types file, we discovered that View and Text use StyleProp<ViewStyle> and StyleProp<TextStyle>. After applying this style type, the style prop on our custom components worked like the style prop on the View and Text components.

This type has allowed us to quickly and easily define style props for all of our custom components. If you’ve experienced similar issues, give it a try.