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?
Yes, you can make dynamic styles. You can pass values from Components.
First create StyleSheetFactory.js
then use it in your component following way
Yes you can and actually, you should use
StyleSheet.create
to create your styles.And then:
Using object spread operator "..." worked for me:
If you still want to take advantage of
StyleSheet.create
and also have dynamic styles, try this out:Notice how the
style
property of theView
is set as an array that combines your stylesheet with your dynamic styles.I usually do something along the lines of:
...
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:
...
If you are using a screen with filters for example, and you want to set the background of the filter regarding if it was selected or not, you can do:
On which set filter is:
PS: the function
this.props.setVenueFilter(filters)
is a redux action, andthis.props.venueFilters
is a redux state.