Global "Text" color and "TextInput" text color

Kuhbaar picture Kuhbaar · Aug 10, 2016 · Viewed 8.6k times · Source

I've started to work with react-native few days ago and after some extensive search I weren't able to find answers for 2 (simple?) questions:

  1. How can I change the color of ALL Text components in react-native? What are the best practices? Creating an own Text component with styling and reusing it everywhere?

  2. Change the default text color of TextInput. I managed to change the placeholder color, and also the underline color in android, but I can't find anything on how to change the input text color (stays black).

  3. Can I change the font / text color for everything anyhow? This option seems to be missing.

Thanks for any help and cheers

Answer

jasonmerino picture jasonmerino · Aug 10, 2016

In order to get consistent styling of Text elements (or any other basic element used in a React Native app) our team has started building out a library of components for our app that match the styles and naming of the style guide put together by our design team.

For example your text component would look like this:

import React, { PropTypes, Component } from 'react';
import ReactNative from 'react-native';    

export default class Text extends Component {

  getProps() {
    const { fontSize, fontWeight } = this.props;
    return {
      fontSize,
      fontWeight,
    };
  }

  render() {
    return (
      <ReactNative.Text {...this.getProps()}>{this.props.children}</ReactNative.Text>
    );
  }
}

Text.propTypes = {
  fontSize: PropTypes.oneOf([
    25,
    20,
    15,
  ]),
  fontWeight: PropTypes.oneOf([
    'normal',
    'bold',
  ]),
};

Text.defaultProps = {
  fontSize: 20,
  fontWeight: 'normal',
};

Creating your text component this way you can define what styles are available and show developers warning if they don't use a valid style with the PropTypes definitions.

We also wanted components in this library to be able to be easily referenced from whatever file you needed them in and so we gave the main library file a name with the providesModule comment that some of the internal React Native components use.

The main library file looks something like this.

/**
 * @providesModule AppNameLibrary
 */

module.exports = {
    get Text() { return require('./Text').default; },
};

Then you just need to import it in whatever component file you need the custom Text component.

import { Text } from 'AppNameLibrary';

That is one way to do it. Not sure if it's the best way, but it's a good way our team has come to build out components so they are designed consistently in a way that matches our style guide.

As far as changing the text color of the Android TextInput component, just assigning a color: 'orange' as a style, changed the text to orange for me. We're using RN 0.28 at this point.