[React.js] - Styled Components Parameters

NoowaH·2022년 1월 25일
0

React.js

목록 보기
4/5
post-thumbnail

Common Components의 재사용성


✅ 공통적으로 사용되는 <input> 의 재사용성을 고려한 스타일링 설정 방식

  • <input icon={<CustomIcon />} /><input /> 2가지 가능성을 고려

const Container = styled.div<{ iconExist: boolean }>`
  input {
    ...
    padding: ${({ iconExist }) => (iconExist ? "0 44 0 11px" : "0 11px")};
    ...
  }
`;

interface IProps extends InputHTMLAttributes<HTMLInputElement> {
  icon?: JSX.Element;
}

const Input: FC<IProps> = ({ icon, ...props }) => {
  return (
    <Container iconExist={!!icon}>
      <input {...props} />
      <div className="input-icon-wrapper">{icon}</div>
    </Container>
  );
};

export default Input;

IProps extends InputHTMLAttributes<HTMLInputElement>

  • input 태그가 가지는 속성들에 대한 타입

  • icon?: JSX.Element : ? == optional | JSX.Element를 받아도, 안받아도 되는 설정


Styled-Components

  • styled-componets 의 props 를 전달하게 되면 div<{ iconExist: boolean }> 와 같이 generics안에 전달한 props값을 가진 객체를 사용

  • iconExist={!!icon} : !! = 확실한 boolean 값 -> undefined의 가능성을 배제

profile
조하운

0개의 댓글