babel-plugin-react-css-modules icon indicating copy to clipboard operation
babel-plugin-react-css-modules copied to clipboard

What is the best way of handling conditional styles together with this plugin?

Open shamilovtim opened this issue 5 years ago • 2 comments

First off, thanks you for this amazing library. It solves a huge problem and really cleans up my code. I know it's a matter of opinion but I'm curious what the most idiomatic / readable / cleanest way to handle conditional styles together with this plugin? Here's my current approach with a functional component. Does anyone have any other patterns?

import React from 'react';
import './Modal.module.scss';

const Modal = (props) => {

  const animateModal = () => {
    if (props.show === true) {
      return('modal animate-in');
    }

    return('modal animate-out');
  }

  return (
    <div styleName={animateModal()}>
      {props.children}
    </div>
  );
};

export default Modal;

shamilovtim avatar May 29 '19 17:05 shamilovtim

I tend to use data-* attributes to handle states.

<div styleName="modal" data-show={props.show}>
  {props.children}
</div>
.modal {
  /* ... */

  &[data-show="true"] {
    display: block; /* or whatever */
  }
}

tyler-dot-earth avatar May 29 '19 17:05 tyler-dot-earth

I use classnames / classcat.

import React from 'react';
import cx from 'classnames';
import './Modal.module.scss';

const Modal = props => (
  <div 
    styleName={cx('modal', {
      'animate-in': props.show,
      'animate-out': !props.show, 
    })}
  >
    {props.children}
  </div>
);

export default Modal;

hinok avatar Jul 30 '19 12:07 hinok