module-based-styling



module-based-styling

0 0


module-based-styling


On Github AndreasArledal / module-based-styling

Module based Styling

Lessons learned

Background

Goal

  • Learning
  • Reuseable components

Importing stylesheet in component

// Webpack config
{
  test: /\.scss$/,
  loaders: [
    'style',
    'css',
    'autoprefixer-loader?browsers=last 2 version', 'sass'
  ]
}
// Components
import 'assets/styles/components/jobs.scss'

Importing stylesheet in component

  • Self contained
  • Everything is still global

CSS has fundamental flaws at scale that can be solved by writing styles in JS. #openyourmind https://t.co/FeesMwPmc8 pic.twitter.com/D5v3ouXnPo

— Vjeux (@Vjeux) November 8, 2014

React Style

Define styles with JavaScript

import Stylesheet from 'react-style';

const styles = Stylesheet.create({
  button: {
    padding: '0.7rem',
    textTransform: 'uppercase'
  }
});

Style components

render() {
  const customColor = { color: this.props.color };
  return (
    <button styles={[styles.button, customColor]}>
      Click me!
    </button>
  );
}

What about variables

It's all Javascript

const variables = {
  brandColor: 'red',
  gutterSize: 40
}

export default variables;
import Stylesheet from 'react-style';
import { brandColor } from 'shared/variables';

const styles = Stylesheet.create({
  button: {
    backgroundColor: brandColor
  }
});

And responsive?

const styles = Stylesheet.create({
  button: {
    width: '4rem'
  },
  '@media screen and (max-device-width: 736px)': {
    button: {
      width: '100%'
    }
  }
});

Pseudo classes?

@withHover
class SubmitButton extends React.Component {
  const styles = Stylesheet.create({
    button: {
      backgroundColor: 'red'
    },
    hover: {
      opacity: '0.8'
    }
  });
  render() {
    const hoverStyle = this.props.hover ? styles.hover : null;
    const buttonStyles = [ styles.button, hoverStyle ];
    return (
      <button styles={buttonStyles}>Click me!</button>
    );
  }
}

Layout?

render() {
  return (
    <InnerContent>
      <h2>Layout can be hard...</h2>
      <p>to handle</p>
    </InnerContent>
  );
}

What was good?

  • Self containment
  • Responsive surprisingly easy
  • Dynamic capabilities

What was bad?

  • Sometimes hard to get an overview in components
  • No pseudo classes and elements
  • Layout
  • DRY was sometimes hard

Would I use it again?

What are the alternatives?

Radium

  • Automatically helps with hover
  • Responsive is bad

CSS-Modules

  • Looks and feels like CSS
  • Everything is local by default
  • It's composable
Module based Styling Lessons learned