ReactNative – coloring text with a prop string

Update: While exploring further, I discovered that my issue was a lack of curly braces and not something more complex! Turns out you don’t need to do this whole thing with a new object, you can just use the var directly in a style parameter, as follows:

      <View style={{ flex: 1, flexDirection: 'row', backgroundColor:this.props.background }}>
        {this.props.children}
      </View>

Or even append it to an existing style:

<View style={[styles.CalcButton, {backgroundColor: this.props.background}]}>

I’ve been exploring ReactNative recently, as an alternative to using Unity3D to develop multi-platform apps for iOS/Android.

While I’m not a big fan of JavaScript, this framework seems to be worth the pain for non-graphic intense apps. I’ve been working through the tutorials and exploring the system myself for my own education. One thing that wasn’t obvious was how to set the color of a piece of text without adding an entry to the style-sheet.

I have a simple hello-world type component that renders a simple greeting with the passed name in props and I wanted to be able to add a color to the greeting, without adding a style-sheet entry.

Ideally I wanted something that looked like this:

<Greeting name="Colin" color="red"/>;

Acting on the name value is pretty trivial, but passing the color string and converting it to a style required some more google searching. I found similar questions and answers but nothing direct, so after a little experimentation, I got the following code to work:

class Greeting extends React.Component{
  render() {
    var colorStyle = Object.assign(
      {color : this.props.color}
    );
    return (
      <Text style={colorStyle}>
        Hello {this.props.name}!</Text>
    );
  }
}

This works by creating an object with a key:value pair of color and the color string passed. This style is then used in the Text object to set the color of the text.

This will work with a hex color too.

Leave a Reply