Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS apply multiple inline styles

Let's say I have the following styles:

const styles = StyleSheet.create({
padding: {
  padding: 10
},
margin: {
  margin: 10
}
});

and I want to apply both of them to a react component?

like image 978
Oscar Franco Avatar asked Jun 23 '16 13:06

Oscar Franco


Video Answer


2 Answers

While I did some research for this, the answer is not inmediatly clear, one suggestion is:

<View style={Object.assign({}, styles.padding, styles.margin)}>
    ...
</View>

Object.assign() takes the list of arguments and merges them, however, if you don't pass the first empty object it will overwrite the first argument, so if you want to keep you styles clean you have to pass it.

However as of react 0.27.2 I got an asign error trying to do this.

Some further reading revealed:

<View style={StyleSheet.flatten([styles.postHeader, styles.flowRight])}>
  ...
</View>

Works just fine, but this is very verbose and not really intuitive, after I while I found another snippet:

<View style={[styles.postHeader, styles.flowRight]}>

For all intents and purposes this was what I was looking for.

I just thought of sharing this knowledge here since it seems fairly obvious but I could not find any documentation for it.

like image 110
Oscar Franco Avatar answered Oct 23 '22 16:10

Oscar Franco


Simplest solution I use it in inline css

 <div style={{color: "yellow", fontSize: 24}}>Style Me</div>

or use by adding classes as

 <div className="section-spac banner-with-whitebg">Style Me</div>
like image 21
Rahul Soni Avatar answered Oct 23 '22 16:10

Rahul Soni