How to combine multiple inline style objects?

In React, you can clearly create an object and designate it as an inline style. ie. mentioned below.

var divStyle = { color: 'white', backgroundImage: 'url(' + imgUrl + ')', WebkitTransition: 'all', // note the capital 'W' here msTransition: 'all' // 'ms' is the only lowercase vendor prefix }; var divStyle2 = {fontSize: '18px'}; React.render(<div style={divStyle}>Hello World!</div>, mountNode); 

How to combine several objects and assign them together?

+166
reactjs
Apr 30 '15 at 23:13
source share
12 answers

If you use React Native, you can use array notation:

 <View style={[styles.base, styles.background]} /> 

See docs for more details.

+322
Jun 24 '16 at 2:54 on
source share

You can use the spread operator:

  <button style={{...styles.panel.button,...styles.panel.backButton}}>Back</button 
+259
May 18 '16 at 12:24
source share

You can do this with Object.assign() .

In your example, you would do:

 ReactDOM.render( <div style={Object.assign(divStyle, divStyle2)}> Hello World! </div>, mountNode ); 

This will combine the two styles. The second style will replace the first, if there are corresponding properties.

As Brandon pointed out, you should use Object.assign({}, divStyle, divStyle2) if you want to reuse divStyle without applying fontSize to it.

I like to use this to create components with default properties. For example, here is a small stateless component with default margin-right :

 const DivWithDefaults = ({ style, children, ...otherProps }) => <div style={Object.assign({ marginRight: "1.5em" }, style)} {...otherProps}> {children} </div>; 

So, we can do something like this:

 <DivWithDefaults> Some text. </DivWithDefaults> <DivWithDefaults className="someClass" style={{ width: "50%" }}> Some more text. </DivWithDefaults> <DivWithDefaults id="someID" style={{ marginRight: "10px", height: "20px"}}> Even more text. </DivWithDefaults> 

Which will give us the result:

 <div style="margin-right:1.5em;">Some text.</div> <div style="margin-right:1.5em;width50%;" class="someClass">Some more text.</div> <div style="margin-right:10px;height:20px;" id="someID">Even more text.</div> 
+43
Dec 04 '15 at 19:33
source share

Unlike React Native, we cannot pass an array of styles to React, for example

 <View style={[style1, style2]} /> 

In React, we need to create a separate style object before passing it to the style property. Like:

 const Header = (props) => { let baseStyle = { color: 'red', } let enhancedStyle = { fontSize: '38px' } return( <h1 style={{...baseStyle, ...enhancedStyle}}>{props.title}</h1> ); } 

We used the ES6 Spread operator to combine the two styles. You can also use Object.assign () for the same purpose.

This also works if you don't need to store your style in var

 <Segment style={{...segmentStyle, ...{height:'100%'}}}> Your content </Segment> 
+25
Dec 17 '17 at 16:28
source share

Object.assign() is a simple solution, but (currently) the top answer is to use it - while just fine for building stateless components, it will cause problems for the OP of the desired goal of merging two state objects.

With two arguments, Object.assign() actually mutates the first object in place, affecting future instances.

Example:

Consider two possible style configurations for the box:

 var styles = { box: {backgroundColor: 'yellow', height: '100px', width: '200px'}, boxA: {backgroundColor: 'blue'}, }; 

Therefore, we want all our blocks to have default styles, but we want to overwrite them with a different color:

 // this will be yellow <div style={styles.box}></div> // this will be blue <div style={Object.assign(styles.box, styles.boxA)}></div> // this SHOULD be yellow, but it blue. <div style={styles.box}></div> 

Once Object.assign() is executed, the 'styles.box' object changes forever.

The solution is to pass an empty object to Object.assign() . In doing so, you tell the method to create a new object with the objects that you pass to it. Like this:

 // this will be yellow <div style={styles.box}></div> // this will be blue <div style={Object.assign({}, styles.box, styles.boxA)}></div> // a beautiful yellow <div style={styles.box}></div> 

This concept of mutating objects in place is critical to React, and the proper use of Object.assign() really useful for using libraries like Redux.

+22
Jun 07 '16 at 18:20
source share

You can also combine classes with inline style like this:

 <View style={[className, {paddingTop: 25}]}> <Text>Some Text</Text> </View> 
+11
Mar 09 '18 at 19:38
source share

To go even further, you can create a helper function classnames -like:

 const styleRules = (...rules) => { return rules.filter(Boolean).reduce((result, rule) => { return { ...result, ...rule }; }, {}); }; 

And then use it conditionally in your components:

 <div style={ styleRules( divStyle, (window.innerWidth >= 768) && divStyleMd, (window.innerWidth < 768) && divStyleSm ) }>Hello World!</div> 
+2
Oct 30 '18 at 12:54
source share

For those looking for this solution in React, if you want to use the distribution operator inside the style, you should use: babel-plugin-transform-object-rest-spread.

Install it using the npm module and configure your .babelrc as follows:

 { "presets": ["env", "react"], "plugins": ["transform-object-rest-spread"] } 

Then you can use as ...

 const sizing = { width: 200, height: 200 } <div className="dragon-avatar-image-background" style={{ backgroundColor: blue, ...sizing }} /> 

Additional information: https://babeljs.io/docs/en/babel-plugin-transform-object-rest-spread/

+1
Sep 20 '18 at 9:52
source share

So basically I look at it wrong. From what I see, this is not a specific React question, but rather a JavaScript question on how to combine two JavaScript objects together (without knocking down similarly named properties).

This StackOverflow answer explains this. How can I combine the properties of two JavaScript objects dynamically?

In jQuery, I can use the extend method.

0
May 01 '15 at 11:24
source share

To expand on what @PythonIsGreat said, I create a global function that will do this for me:

 var css = function(){ var args = $.merge([true, {}], Array.prototype.splice.call(arguments, 0)); return $.extend.apply(null, args); } 

This deeply extends the objects into a new object and allows a variable number of objects as parameters. This allows you to do something like this:

 return( <div style={css(styles.base, styles.first, styles.second,...)} ></div> ); var styles = { base:{ //whatever }, first:{ //whatever }, second:{ //whatever } } 
0
Jul 23 '15 at 18:17
source share

I built a module for this if you want to add styles based on a condition, for example:

 multipleStyles(styles.icon, { [styles.iconRed]: true }) 

https://www.npmjs.com/package/react-native-multiple-styles

0
Nov 10 '16 at 15:12
source share

Ways of embedded modeling:

 <View style={[styles.red, {fontSize: 25}]}> <Text>Hello World</Text> </View> <View style={[styles.red, styles.blue]}> <Text>Hello World</Text> </View> <View style={{fontSize:10,marginTop:10}}> <Text>Hello World</Text> </View> 
0
Dec 13 '18 at 5:33
source share



All Articles