Search code examples
cssreactjsstylesheet

Extend common CSS definition in React


I am writing a simple React component where I change the component style when the mouse pointer is on the component. I was able to make my component work but I have two stylesheets that are almost similar. One style is used for onMouseOver and the other is used for onMouseOut event. The difference between the two stylesheets is only one line: the border definition.

I would like to avoid duplicated CSS definitions and I would like to simplify my CSS according to the following:

  • one basic stylesheet which describes the looking of the component
  • one style extends basic for onMouseOver event (contains only border)
  • another style extend basic for onMouseOut event (contains only border)

This is the stylesheet definition that I would like to use:

const STYLE = {
  box: {
     '-moz-border-radius': '15px',
     '-moz-box-shadow': '#B3B3B3 13px 13px 13px',
     '-webkit-box-shadow': '#B3B3B3 13px 13px 13px',
     'background-color': '#E3A20B',
     'border-radius': '15px',
     'border': '5px solid #FFFF00',
     'box-shadow': '#B3B3B3 13px 13px 13px',
     'float': 'left',
     'height': '215px',
     'margin': '15px',
     'width': '150px'
  },

  boxMouseOver: {
    'border': '5px solid #000000',
  },

  boxMouseOut: {
    'border': '5px solid #FFFF00',
  }
}

This is my working code uses two stylesheets:

<div style={this.state.mouseOver ? STYLE.boxOver : STYLE.boxDefault} onMouseOver={...} onMouseOut={...}>
    ...
</div>

And this is what I would like to do, but unfortunately it does not work:

<div style={STYLE.box, this.state.mouseOver ? STYLE.boxMouseOver : STYLE.boxMouseOut} onMouseOver={...} onMouseOut={...}>
    ...
</div>

What is the proper way to add two different styles to a component OR how I can extend the STYLE.box constant and redefine the border property in descent stylesheets?


Solution

  • const STYLE = {
      box: {
        '-moz-border-radius': '15px',
        '-moz-box-shadow': '#B3B3B3 13px 13px 13px',
        '-webkit-box-shadow': '#B3B3B3 13px 13px 13px',
        'background-color': '#E3A20B',
        'border-radius': '15px',
        'border': '5px solid #FFFF00',
        'box-shadow': '#B3B3B3 13px 13px 13px',
        'float': 'left',
        'height': '215px',
        'margin': '15px',
        'width': '150px'
      },
    
      boxMouseOver: {
        'border': '5px solid #000000',
      },
    
      boxMouseOut: {
        'border': '5px solid #FFFF00',
      }
    }
    
    <div style={{...STYLE.BOX, ...(this.state.mouseOver ? STYLE.boxOver : STYLE.boxDefault)}} onMouseOver={...} onMouseOut={...}>
        ...
    </div>

    This must work