Pete Thorne Pete Thorne - 1 month ago 13
React JSX Question

Can I make dynamic styles in React Native?

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 to have each one individual.

Any tips?

Answer

I usually do something along the lines of:

<View style={jewelStyle()} />

...

jewelStyle = function(options) {
   return {
     borderRadius: 10,
     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,
   }
 }
Comments