본문 바로가기

Typescript

Typescript (3) Optional Props

Component에 props를 지정해 줄 때 가끔은 optional props를 지정해 줘야 될 때가 있다

 

예)

import React from "react";
import Square from "./Square";

function App() {
  return (
    <div>
      <Square txtColor="black" bgColor="teal" />
      <Square bgColor="teal" />
    </div>
  );
}

export default App;

이런식으로 첫 번째 square component는 txtColor가 필요하고 두 번째 square component는 txtColor이 필요 없다

 

예)

 

import styled from "styled-components";

interface WrapperProps {
  bgColor: string;
  txtColor: string;
}

const Wrapper = styled.div<WrapperProps>`
  background-color: ${(props) => props.bgColor};
`;

interface bgColorProps {
  bgColor: string;
  txtColor: string;
}

function Square({ bgColor, txtColor }: bgColorProps) {
  return <Wrapper bgColor={bgColor} />;
}

export default Square;

 

우선 square component에서 txtColor을 갖고 오고 bgColorProps interface 안에 txtColor type에 대해 추가해 줬다

하지만 이렇게 하게 되면 에러가 뜨는데 그 이유는 두 번째 square component는 txtColor props가 없기 때문이다

interface 안에 prop types를 넣게 되면 component를 부를 때 그 props들이 required가 된다

하지만 txtColor처럼 optional props에 경우 다른 방법으로 interface에서 지정해줘야 된다

 

예)

import styled from "styled-components";

interface WrapperProps {
  bgColor: string;
  txtColor: string;
}

const Wrapper = styled.div<WrapperProps>`
  background-color: ${(props) => props.bgColor};
`;

interface bgColorProps {
  bgColor: string;
  txtColor?: string;
}

function Square({ bgColor, txtColor }: bgColorProps) {
  return <Wrapper bgColor={bgColor} txtColor={txtColor ?? bgColor} />;
}

export default Square;

 

bgColorProps 안에 txtColor을 설명해 줄 때 앞에 물음표를 넣으면 optional props가 된다

또한 Wrapper에서 txtColor을 쓸 때에 square component가 txtColor을 받아오지 않는 경우 txtColor을 bgColor로 쓴다고 지정한 걸 볼 수 있다

'Typescript' 카테고리의 다른 글

Typescript (5) Forms  (0) 2023.03.04
Typescript (4) useState  (0) 2023.03.04
Typescript (3) Props 사용하기  (0) 2023.03.04
Typescript (2) Props  (0) 2023.03.04
Typescript (1) Typescript  (2) 2023.03.04