기록

짧음) React에서 제공하는 타입

als982001 2023. 6. 27. 23:34

 CSS 연습을 하던 도중, Container를 자주 쓰는 것 같아 따로 분리하기로 하였다.

// Container.tsx
import styled from "styled-components";

interface IProps {
  children: React.ReactNode;
}

const Div = styled.div`
  width: 80%;
  min-width: 200px;
  height: 200px;
  border: 2px solid black;
  border-radius: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
`;

export default function Container(props: IProps) {
  return <Div>{props.children}</Div>;
}

// Button예시.tsx
import styled from "styled-components";
import Container from "../Container";

const MyButton = styled.button``;

export default function Button05() {
  return (
    <>
      <Container>
        <MyButton>Join now</MyButton>
      </Container>
    </>
  );
}

Container를 따로 분리하여 위의 코드처럼 이용할 수 있었다. 처음에는 Container.tsx에서 props의 타입을 any로 설정했는데, 혼자 다른 것을 연습할 때는 크게 신경쓸 필요가 없지만, 미래를 위해서 저 props의 타입에 대해 알 필요가 있다고 생각했다. 그리고 특별한 이유가 이씨 않는 한, 타입을 any로 설정하는 것은 타입스크립트가 제공해주는 방어막을 자기 손으로 갖다 버리는 꼴이라 생각하기도 한다. 그래서 찾아보니, React.ReactNode라는 타입이 있다고 한다. 이는 모든 종류의 React 요소를 나타내기 위한 타입이며, 컴포넌트의 자식 요소로 사용될 수 있는 모든 것을 포함한다고 한다. 이 외에도 React에서 제공하는 다양한 타입이 있다.

  • React.ReactNode: 모든 종류의 React 요소를 나타내는 타입
  • React.FC: 함수형 컴포넌트를 정의하기 위한 타입
  • React.Component: 클래스형 컴포넌트를 정의하기 위한 타입
  • React.ComponentProps: 컴포넌트의 프로퍼티 타입을 추출하기 위한 유틸리티 타입
  • React.ReactElement: React 요소를 나타내는 타입
  • React.ComponentType: 임의의 컴포넌트 타입을 나타내는 타입
  • 등등...