Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override react native style

I want to override some sub-component of style in react native.like - I have created an style CircleShapeView

 const styles = StyleSheet.create({
      CircleShapeView: {
        width: 50,
        height: 50,
        borderRadius: 50/2,
        backgroundColor: '#000'
    },
    });

I want change backgroundColor ,when i am usins this style. some thing like this.

<Image
style={backgroundColor: "#fff", styles.CircleShapeView}                   
...
/>  

What is right way to do it?

like image 536
Khemraj Sharma Avatar asked Feb 16 '18 09:02

Khemraj Sharma


2 Answers

To override the backgroundColor, you could just do this:

<Image
style={[ styles.CircleShapeView, { backgroundColor: "#fff" } ]}                   
...
/> 

A more flexible way of overriding style would be to pass an additional style prop to your subcomponent.

You would call your subcomponent like that:

<Subcomponent passedStyle={{ backgroundColor: '#fff' }} /> 

Apply passed style to your image:

<Image
style={[ styles.CircleShapeView, this.props.passedStyle ]}                   
...
/> 
like image 109
Tim Avatar answered Oct 02 '22 07:10

Tim


To add to the other answers here, make sure that you are specifying the inherited props style AFTER the style on the component you are trying to override.

Example: Do this:

<Image
   style={[ styles.CircleShapeView, this.props.passedStyle ]}                   
   ...
/> 

Not this:

<Image
   style={[ this.props.passedStyle, styles.CircleShapeView ]}                   
   ...
/> 

The second example will NOT override the style on the component.

like image 35
OffensivelyBad Avatar answered Oct 02 '22 07:10

OffensivelyBad