Reputation: 104
This question is about using an array arg for the styling prop on a react component:
style={[styles.localTextStyle, textStyle...]}
As I understand precedence is from last element to first. So in the example above textStyle would overwrite styles.localTextStyle. This is good, however, I am making a custom component and I want to be able to specify inline props from the parent and have the inline be of highest precedence yet not overwrite previous styles if no prop is provided.
For example, if I were writing a custom component called Text:
<Text style={[styles.localTextStyle, textStyle, {
color: color
}]}>
I would use localTextStyle
as defaults then styling passed from parent called textStyle
, and finally the prop called color
to set the color. This only works when the prop color
is defined, otherwise, it will overwrite color
to unset despite it possibly being set in textStyle
for earlier styling.
So I'm wondering what the best way to circumvent this is. I currently have wrapped the final arg in a function called Clean
which returns a new object with only defined keys-values. That works but it makes the code messy and I'd be shocked if someone didn't have a smarter, better way to do this.
<Text style={[styles.localTextStyle, textStyle, Clean({
color: color
})]}>
Upvotes: 2
Views: 1270
Reputation: 166
It's written inside the Documentation that :
You can also pass an array of styles - the last style in the array has precedence, so you can use this to inherit styles.
And I checked and It's like that :
[Component-Style] < [inside-array] < [outside-the-array]
like this :
<TSButton style={[Style.button,{padding:0,width:50,height:20}]} />
So here the priority is as >>
TSButton Styling < Style.button < padding , width, ...
Upvotes: 3