2022-02-25 TIL TypeScript for styled-components, optional Props

Romuru·2022년 2월 25일
0

TIL

목록 보기
2/10

/ Circle.tsx

import styled from "styled-components";

interface ContainerProps {
   bgColor:string; 
   borderColor: string;
}


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


interface CircleProps {
    bgColor: string;
    borderColor?: string; 
}

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


export default Circle;

/ App.tsx

import React from 'react';
import styled from "styled-components";
import Circle from './Circle';


function App() {
  return(
    <div>
      <Circle bgColor="tomato"/>
      <Circle bgColor="skyblue" borderColor="blue" />
    </div>
    );
}

export default App;

typing props

  1. container props type을 지정한다

  2. container 의 styled-componets 를 부여하고 1의 타입을 부여한다.

  3. Circle의 props type을 지정한다.

  4. 3의 타입을 지정한다.

component Circle 은 CircleProps에게서 bgColor type을 지정받고

인자로 받은 bgColor과함께 Container styled-component를 반환한다.

Container은 width 200px height 200px 를 가지고있고

backgrond-color는 props .bgColor로 받고 있으며

type 지정은 interface ContainerProps 에서 받고있기에

로 component를 사용하면

"토마토" 와 "하늘색" 을 가진 원 두개가 출력되는것이다.

props optional

props type를 선택적인 props 를 지정할 때.

기본적으로 props type을 지정하면 required 상태인데,

이를 해결해주기 위해서는

bgColor: string;
borderColor?: srting;

와 같이 옵션에 ?를 붙여주면 된다

하지만 styled-component에 전달을 해줘야할때는

위와같은 작업을 하더라도 css 상에서는 여전히 required 상태이기 때문에

borderColor={borderColor ?? bgColor}

로 Null 병합 연산자를 이용해 해결할 수 있다.
(?? 앞에 값이 null 이거나 undefined라면 오른쪽값을, 아니면 왼쪽값을 반환하는 논리연산자.)

profile
늘 새로운 호기심을 찾고, 기술적 한계에 도전하고, 하늘색이 잘 어울리는 사람입니다.

0개의 댓글