본문 바로가기
{React}

10.23.22{코딩일기}벨로퍼트와 함께하는 모던리액트 2-3챕터리뷰(3)

by Davey 2022. 10. 24.
728x90

[ 새롭게 알게 된 것 ]


1. Button에 color props를 넣어주었다면 해당 컴포넌트 CSS도 props로 color변경해줘야됨


color도 넣어주고 app.js theme도 설정 다 했는데 여전히  바뀌지 않는다면? 버튼 색깔에 당황하지 말고

기존에 고정되어 있던 블루 배경색을

 /* 색상 */
  background: #228be6;
  &:hover {
    background: ${lighten(0.1, '#228be6')};
  }
  &:active {
    background: ${darken(0.1, '#228be6')};
  }

아래처럼 props를 변수로 받아 활용해주면 간단히 해결됨을 확인했음

  /* 색상 */
  ${props => {
    const selected = props.theme.palette[props.color];
    return `
      background: ${selected};
      &:hover {
        background: ${lighten(0.1, selected)};
      }
      &:active {
        background: ${darken(0.1, selected)};
      }
    `;
  }}

이 부분을 반드시 color로 넘겨줘야됨을 알게됨. 

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

안그러면 default 값에 따라 걍 계속 blue가 됨. 사실 이것도 처음엔

${props => {

    const selected = props.theme.palette.blue; 로 값을 받는 방식 대체방식임.

}

Button.defaultProps = {
  color: 'blue'
};

이렇게 내비 뒀더니 props값이 파라미터로 넘겨받은 값으로 최신반영이 안되었음.

function Button({ children, ...rest }) {
  return <StyledButton {...rest}>{children}</StyledButton>;
}

마음에 평화가 찾아오는 색상임


 

2. props.theme.palette.blue 이런식으로 값을 받는 대신 비구조화 할당으로 가독성 높일 수 있음


단순히 ${props => {...}} 보다 파라미터가 무엇이 넘겨지는지 분명히 알 수 있어서 좋음.

아니면 JSDoc을 활용할 수 있겠다는 생각도 듦.

 /* 색상 */
  ${({ theme, color }) => {
    const selected = theme.palette[color];
    return css`
      background: ${selected};
      &:hover {
        background: ${lighten(0.1, selected)};
      }
      &:active {
        background: ${darken(0.1, selected)};
      }
    `;
  }}

아니면 메소드로 빼도 좋음. 이게 바로 일급객체의 장점이 아닌가 싶은 모먼트.

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

그리고 이런 방식이 유지보수에도 좋음을 알게됨

 /* 색상 */
  ${colorStyles}

 

3. 컴포넌트 태그 사이즈의 경우 중복되는 CSS코드는 아래와 같이 리팩토링 하는게 좋음을 알게됨


기존에 이러했다면

const sizeStyles = css`
  ${props =>
    props.size === 'large' &&
    css`
      height: 3rem;
      font-size: 1.25rem;
    `}

  ${props =>
    props.size === 'medium' &&
    css`
      height: 2.25rem;
      font-size: 1rem;
    `}

    ${props =>
      props.size === 'small' &&
      css`
        height: 1.75rem;
        font-size: 0.875rem;
      `}
`;

리팩토링하면 이렇게 코드 구조가 명확해짐

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};
  `}
`;

리팩토링한 후 원하는 대로 잘 렌더링되는지 확인 필수임.


728x90

댓글