본문 바로가기
개발

Styled Components 적용하기(React + Typescript)

by rious275 2023. 3. 19.

styled-components 설치

styled-components@types/styled-components를 함께 설치해준다.

yarn add styled-components
yarn add --dev @types/styled-components

기본 적용

import styled from "styled-components";

const App = () => {
  return (
    <div>
      <StyledButton>color change</StyledButton>
    </div>
  );
}

const StyledButton = styled.button`
  width: 200px;
  height: 50px;
  font-size: 16px;
`;

간단 예제

클릭 시 버튼의 색이 변경되는 예제

const App = () => {
  const [color, setColor] = useState<string>("yellow");

  const handleClick = () => {
    if (color === "yellow") setColor("blue");
    else setColor("yellow");
  };

  return (
    <StyledButton color={color} onClick={handleClick}>
      색 변경
    </StyledButton>
  );
};

const StyledButton = styled.button<{ color: string }>`
  width: 200px;
  height: 50px;
  font-size: 16px;
  background-color: ${({ color }) => color};
  color: ${({ color }) => color === "blue" && "white"};
`;