Object.assign()
is an easy solution, but the (currently) top answer's usage of it — while just fine for making stateless components, will cause problems for the OP's desired objective of merging two state
objects.
With two arguments, Object.assign()
will actually mutate the first object in-place, affecting future instantiations.
Ex:
Consider two possible style configs for a box:
var styles = {
box: {backgroundColor: 'yellow', height: '100px', width: '200px'},
boxA: {backgroundColor: 'blue'},
};
So we want all our boxes to have default 'box' styles, but want to overwrite some 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's blue.
<div style={styles.box}></div>
Once Object.assign()
executes, the 'styles.box' object is changed for good.
The solution is to pass an empty object to Object.assign()
. In so doing, you're telling the method to produce a NEW object with the objects you pass it. Like so:
// 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 notion of objects mutating in-place is critical for React, and proper use of Object.assign()
is really helpful for using libraries like Redux.