Can I make dynamic styles in React Native?

Pete Thorne picture Pete Thorne · Mar 31, 2015 · Viewed 144.2k times · Source

Say I have a component with a render like this:

<View style={jewelStyle}></View>

Where jewelStyle =

  {
    borderRadius: 10,
    backgroundColor: '#FFEFCC',
    width: 20,
    height: 20,
  },

How could I make the background colour dynamic and randomly assigned? I've tried

  {
    borderRadius: 10,
    backgroundColor: getRandomColor(),
    width: 20,
    height: 20,
  },

But this makes all instances of View have the same colour, I want each one to be unique.

Any tips?

Answer

Jimmie Berg picture Jimmie Berg · Mar 31, 2015

I usually do something along the lines of:

<View style={this.jewelStyle()} />

...

jewelStyle = function(options) {
   return {
     borderRadius: 12,
     background: randomColor(),
   }
 }

Every time View is rendered, a new style object will be instantiated with a random color associated with it. Of course, this means that the colors will change every time the component is re-rendered, which is perhaps not what you want. Instead, you could do something like this:

var myColor = randomColor()
<View style={jewelStyle(myColor)} />

...

jewelStyle = function(myColor) {
   return {
     borderRadius: 10,
     background: myColor,
   }
 }