React Radium Class Style Overrides

414 views Asked by At

I am trying to write clean and DRY code styles with Radium. This is what my button is so far.

/**
*
* Button
*
*/

import React, { PropTypes } from 'react';
import Radium from 'radium';

const styles = {
  base: {
    borderRadius: '3px',
    backgroundColor: '#23cdf4',
    fontSize: '13px',
  },
  primaryBlue: {
    backgroundColor: '#23cdf4',
  },
  primaryBlueBig: {
    borderRadius: '8px',
    fontSize: '16px',
    padding: '14px 28px',
  },
  primaryRed: {
    backgroundColor: '#F99CAC',
  },
};

class Button extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <button
        style={[styles.base, styles[this.props.type], this.props.style]}
      >
        {text}
      </button>
    );
  }
}

Button.propTypes = {
  text: PropTypes.any,
  type: PropTypes.oneOf(['primaryBlue', 'primaryBlueBig']).isRequired,
  style: PropTypes.object,
  disabled: PropTypes.bool,
};

export default Radium(Button);

Two things I cannot figure out:

  1. How can I extend the background color used by primaryBlue into primaryBlueBig without repeating myself?
  2. How can I change the background color of both blue buttons if the disabled is true?

This is a slimmed down version of what I am currently working with and am trying to get away from having giant if else blocks in the render function. Thanks! ^.^

1

There are 1 answers

2
Bertrand Marron On BEST ANSWER

You can use modifiers.

This is basically what you’re already doing, but with a little more refactoring.

I would define the styles a little differently:

const styles = {
  base: {
    borderRadius: '3px',
    backgroundColor: '#ffffff',
    fontSize: '13px',
  },

  primaryBlue: {
    backgroundColor: '#23cdf4',
  },
  primaryRed: {
    backgroundColor: '#F99CAC',
  },

  big: {
    borderRadius: '8px',
    fontSize: '16px',
    padding: '14px 28px',
  },

  disabled: {
    primaryBlue: {
      backgroundColor: '#eeeeee',
    },
    primaryRed: {
      backgroundColor: '#eff0f1',
    }
  }
};

Then you can have a big and a disabled prop.

return (
  <button
    style={[
      styles.base,
      styles[this.props.type],
      this.props.big && styles.big,
      this.props.disabled && styles.disabled[this.props.type]
    ]}>
    {text}
  </button>
);