Search code examples
reactjssassmaterial-components-web

React Button - Material Components for Web - Secondary Styling with SASS


I'm creating a React Button component using Material Components Web. I've gotten the default button working which uses the Primary theme colour. I'd like to add an option for a secondary coloured button, but I'm not sure how to do this with the sass mixins.

I found this feature request but the answer is out of date as the Button styles have been refactored. Can someone point me in the right direction?

Here's my Button implementation:

Button.js

import './Button.scss';
import { useEffect, useRef } from 'react';
import { MDCRipple } from '@material/ripple';
import PropTypes from 'prop-types'
import classNames from 'classnames';

function Button(props) {
  const buttonElement = useRef(null);

  useEffect(() => {
    const ripple = new MDCRipple(buttonElement.current);
    return () => {
      ripple.destroy();
    }
  }, []);

  const btnClassNames = classNames({
    'mdc-button': true,
    'mdc-button--outlined': props.outlined,
    'mdc-button--raised': props.contained,
    'mdc-button--unelevated': props.unelevated,
    'mdc-button--icon-leading': props.icon,
    'ids-button-secondary': props.secondary
  });

  const renderIcon = (icon) => {
    return(<i className="material-icons mdc-button__icon" aria-hidden="true">{icon}</i>);
  }

  return (
    <button className={btnClassNames} ref={buttonElement} onClick={props.onClick} disabled={props.disabled}>
      <span className="mdc-button__ripple"/>
      { props.icon ? renderIcon(props.icon) : null }
      <span className="mdc-button__label">
        { props.children }
      </span>
      { props.trailingIcon ? renderIcon(props.trailingIcon) : null }
    </button>
  );
}

Button.propTypes = {
  outlined: PropTypes.bool,
  contained: PropTypes.bool,
  unelevated: PropTypes.bool,
  icon: PropTypes.string,
  trailingIcon: PropTypes.string,
  onClick: PropTypes.func,
  disabled: PropTypes.bool,
  secondary: PropTypes.bool,
}

export default Button;

theme.js

@forward '~@material/theme' with (
  $primary: #570D9E,
  $secondary: #43B02A,
  $background: #fff,
);

Button.scss

@use './theme';
@use "~@material/button/mdc-button";
@use "~@material/button/_mixins";

.ids-button-secondary {
   < what do I implement here? >
}

Solution

  • @use './theme';
    @use "~@material/button/mdc-button";       // This line injects button's core styles
    @use "~@material/button";                  // This line "imports" button's mixins
    
    .ids-button-secondary {
      @include button.filled-accessible(red);  // This mixin sets fill color for a contained button.
    }
    

    This is just an example of customized button. There are a number of mixins to customize other properties like text color, icon color, size, shape, etc. See the latest docs here.