Month: January 2020

React inline styles – merge two style objects

Posted on Updated on

I had two style objects that I needed to merge for a component. One was the style objects that makes the component look good, the other was to set the display visible or not.

I could get around it by wrapping the component in another div that would get the display style, but here is how to minimize your divs

const style1 = {color: ‘blue’}
const style2 = {display: ‘none’} //used with state that toggles visibility

<div style={Object.assign(style2, style1)} > </div>

The reason the display style should be first is because the key pairs from the second object are copied to the first. so style2 would now be

{display: ‘none’, color: ‘blue’}

 

Advertisement