[리액트 마스터 클래스] React+TypeScript에서의 Props 사용 방법

Carrie·2023년 9월 27일
0

React와 TypeScript에서의 Props 사용 방법을 알아보자! 아래 코드는 Circle 컴포넌트를 만들고, App에서 Circle 컴포넌트를 렌더링하는 간단한 로직이다.

App 컴포넌트 설정

App.tsx
Circle 컴포넌트를 import한 후 두 개의 Circle을 렌더링하여 각각의 props를 전달한다.

import Circle from "./Circle";
function App() {
  return (
    <div>
      <Circle bgColor="teal" borderColor="black"/>
      <Circle bgColor="tomato" text="I'm here!"/>
    </div>
  );
}
export default App;

Circle 컴포넌트에서의 interface 사용

Circle.tsx
interface를 사용해 객체의 타입을 TypeScript에게 설명해준다. TypeScript의 interface는 코드 실행 전에 오류를 확인해주기 때문에 매우 유용하다.

interface CircleProps {
  bgColor: string;
}

interface로 타입을 명시해주고, 아래와 같이 사용한다. 'bgColor는 CircleProps의 프로퍼티이며, 타입은 string이다.' 라는 의미이다.

function Circle({ bgColor }: CircleProps) {

Required Props와 Optional Props

Optional Props로 설정하고 싶은 경우 ?만 추가해주면 된다!

interface CircleProps {
  bgColor: string; // 필수 props
  borderColor?: string; // 선택 props
  text?: string; // 선택 props
}

borderColor?: string;borderColor: string | undefined의 의미와 같다.

Optional Props의 Default Value 설정

??를 사용하여 'borderColor가 undefined 상태라면 bgColor를 적용한다'는 로직을 설정한다.

<Container bgColor={bgColor} borderColor={borderColor ?? bgColor}>

Props의 적용

App으로 부터 받은 bgColor를 Container에 보내준다.

<Container bgColor={bgColor} />

그런데 여기서 TypeScript는 Container가 어떤 props를 받아야 하는지 모르기 때문에 문제가 발생한다. Container가 받는 props를 TypeScript에게 설명해주기 위해 <CircleProps>를 추가한다.

const Container = styled.div<CircleProps>`

전달받은 props를 사용해 background-color를 설정한다.

background-color: ${(props) => props.bgColor};

Circle.tsx 전체 코드

import styled from "styled-components";

interface CircleProps {
  bgColor: string; // 필수 props
  borderColor?: string; // 선택 props
  text?: string; // 선택 props
}

// CircleProps와 ContainerProps는 동일하기 때문에 CircleProps로 통일해서 사용한다.
// interface ContainerProps {
//     bgColor: string;
//     borderColor: string;
// }

function Circle({ bgColor, borderColor, text="default text" }: CircleProps) {
  return (
    <Container bgColor={bgColor} borderColor={borderColor ?? bgColor}>
      {text}
    </Container>
  );
}

const Container = styled.div<CircleProps>`
  width: 200px;
  height: 200px;
  background-color: ${(props) => props.bgColor};
  border-radius: 50%;
  border: 1px solid ${(props) => props.borderColor};
`;

export default Circle;
profile
Markup Developer🧑‍💻

0개의 댓글