Skip to content

Latest commit

 

History

History
74 lines (61 loc) · 1.33 KB

03.style-functions.md

File metadata and controls

74 lines (61 loc) · 1.33 KB

Style Functions

Since we’re using JavaScript, we can also employ helper functions for styling elements.

Example 1

A function to create rgba values of black

const darken = (n) => `rgba(0, 0, 0, ${n})`;
darken(1 / 8); // 'rgba(0, 0, 0, 0.125)'

const shade = [
  darken(0),
  darken(1 / 8),
  darken(1 / 4),
  darken(3 / 8),
  darken(1 / 2),
  darken(5 / 8),
  darken(3 / 4),
  darken(7 / 8),
  darken(1)
];
// Now, shade[4] is 'rgba(0, 0, 0, 0.5)'

Example 2

Creating a scale for margin and padding to help keep visual rhythm consistent

// Modular powers of two scale
const scale = [
  0,
  8,
  16,
  32,
  64
];

// Functions to get partial style objects
const createScaledPropertyGetter = (scale) => (prop) => (x) => {
  return (typeof x === 'number' && typeof scale[x] === 'number')
    ? {[prop]: scale[x]}
    : null
};
const getScaledProperty = createScaledPropertyGetter(scale);

export const getMargin = getScaledProperty('margin');
export const getPadding = getScaledProperty('padding');
// Style function usage
const Box = ({
  m,
  p,
  ...props
  }) => {
  const sx = {
    ...getMargin(m),
    ...getPadding(p)
  };

  return <div {...props} style={sx}/>
};

// Component usage
const Box = () => (
  <div>
    <Box m={2} p={3}>
      A box with 16px margin and 32px padding
    </Box>
  </div>
);