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

  1. const darken = (n) => `rgba(0, 0, 0, ${n})`;
  2. darken(1 / 8); // 'rgba(0, 0, 0, 0.125)'
  3. const shade = [
  4. darken(0),
  5. darken(1 / 8),
  6. darken(1 / 4),
  7. darken(3 / 8),
  8. darken(1 / 2),
  9. darken(5 / 8),
  10. darken(3 / 4),
  11. darken(7 / 8),
  12. darken(1)
  13. ];
  14. // So now,
  15. // shade[4] is 'rgba(0, 0, 0, 0.5)'

Example 2

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

  1. // Modular powers of two scale
  2. const scale = [
  3. 0,
  4. 8,
  5. 16,
  6. 32,
  7. 64
  8. ];
  9. // Functions to get partial style objects
  10. const createScaledPropertyGetter = (scale) => (prop) => (x) => {
  11. return (typeof x === 'number' && typeof scale[x] === 'number')
  12. ? {[prop]: scale[x]}
  13. : null
  14. };
  15. const getScaledProperty = createScaledPropertyGetter(scale);
  16. export const getMargin = getScaledProperty('margin');
  17. export const getPadding = getScaledProperty('padding');
  18. // Style function usage
  19. const Box = ({
  20. m,
  21. p,
  22. ...props
  23. }) => {
  24. const sx = {
  25. ...getMargin(m),
  26. ...getPadding(p)
  27. };
  28. return <div {...props} style={sx}/>
  29. };
  30. // Component usage
  31. const Box = () => (
  32. <div>
  33. <Box m={2} p={3}>
  34. A box with 16px margin and 32px padding
  35. </Box>
  36. </div>
  37. );