[React] Style Component

Suyeon·2020년 8월 21일
1

React

목록 보기
1/26
post-thumbnail

1️⃣ Sass

Install
npm install node-sass

Use dynamic class name

  • className={['Button', size].join(' ')}
  • className={`Button ${size}`}
  • classnames library

How to use

// App.js
function App() {
  return <Button size="large" color="grey">BUTTON</Button>
}
// Button.scss
$blue: #228be6;
$grey: #495057;

@mixin button-color($color) {
  background: $color; 
  
  &:hover { ... }
  &:active { ... }
}

.Button {
 ...

  // Size
  &.large { ... }
  &.medium { ... }
  &.small { ... }

  // Color
  &.blue { @include button-color($blue); }
  &.gray { @include button-color($gray); }
}

...Rest Props

  • When you wanted to further hand off these items (i.e., thing1 and thing2) down to the nested tag
// (*)
<Component
  thing1={ props.thing1 }
  thing2={ props.thing2 } />

//(**) ...props
<Component { ...props } />

2️⃣ Module

  • Box.module.css
  • Use uniqe class name
  • Install node-sass when use it with sass

3️⃣ Styled-components

  • Use utility css function: polished library (like darken)

Css helper

  • Generate CSS from a template literal with interpolations
const Circle = styled.div`
  width: 5rem;
  height: 5rem;
  background: ${props => props.color || 'black'};
  ${props =>
    props.huge &&
    css`
      width: 10rem;
      height: 10rem;
    `}
`;

<Circle color="red" huge />;

ThemeProvider

  • Global Variables
// App.js
function App() {
  return (
    <ThemeProvider
      theme={{
        palette: {
          blue: '#228be6',
          gray: '#495057',
          pink: '#f06595'
        }
      }}
    >
      <AppBlock>
        <Button>BUTTON</Button>
      </AppBlock>
    </ThemeProvider>
  );
}

// Button.js
const colorStyles = css`
  ${({ theme, color }) => {
    const selected = theme.palette[color];
    return css`
      background: ${selected};
      &:hover { background: ${lighten(0.1, selected)}; }
    `;
  }}
`;

const sizes = {
  large: {
    height: '3rem',
    fontSize: '1.25rem'
  },
  medium: {
    height: '2.25rem',
    fontSize: '1rem'
  },
  small: {
    height: '1.75rem',
    fontSize: '0.875rem'
  }
};

const sizeStyles = css`
  ${({ size }) => css`
    height: ${sizes[size].height};
    font-size: ${sizes[size].fontSize};
  `}
`;

const StyledButton = styled.button`
  /* Common Style */

  /* Size */
  ${sizeStyles}

  /* Color */
  ${colorStyles}
`;

// Modify Button Component
const ShortMarginButton = styled(Button)`
  & + & {
    margin-left: 0.5rem;
  }
`;

function Button({ children, color, size,  ...rest }) {
  return (
    <StyledButton color={color} size={size} {...rest}>
      {children}
    </StyledButton>
  );
}
profile
Hello World.

0개의 댓글