React + Typescript

김주형·2023년 3월 7일
0

react 환경에서 typescript를 세팅해보자

yarn create react-app my-app --template typescript

props type 정의하기

prop-types는 코드를 실행한 후 오류를 알려주지만

typescript를 사용하는 이유는 코드가 실행되기 전에 오류를 확인할 수 있다.

// App.tsx

import Circle from './Circle';

function App() {
  return (
    <>
      <Circle bgColor='teal' text='hi' borderColor='red' />
      <Circle bgColor='tomato' />
      <Circle bgColor='red' />
    </>
  );
}

export default App;
//Circle.tsx

import React, { useState } from 'react';
import styled from 'styled-components';

// styled component에서 쓰기 위한 interface
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};
`;

// props interface
interface CircleProps {
  bgColor: string; // required
  borderColor?: string; // optional
  text?: string; // optional
}

const Circle = ({ bgColor, borderColor, text = 'im here' }: CircleProps) => {
  const [value, setValue] = useState<string>('');

  return (
    <Container bgColor={bgColor} borderColor=```
코드를 입력하세요
```{borderColor ?? bgColor}>
      {text}
      {value}
    </Container>
  );
};

export default Circle;

1.interface 는 object의 타입을 정의한다.
2.interface 는 required 혹은 ? 연산자를 통해 optional로 사용할 수 있음
3.리액트의 props의 타입을 정의하기 위해 props를 받는 컴포넌트에서 interface로 props의 타입을 알려준다.

interface CircleProps {
  bgColor: string; // required
  borderColor?: string; // optional
  text?: string; // optional
}

Circle 컴포넌트에 props로 bgColor , borderColor , text 를 전달할 때 bgColor 은 required로써 반드시 전달해야 하지만 , borderColor , text 는 optional로 props를 전달해도 되고 안해도되는 선택사항이다.

4.props의 기본값을 설정해준다.(기본 자바스크립트 문법)

const Circle = ({ bgColor, borderColor, text = 'im here' }: CircleProps) => { ... }

text라는 props의 type을 알아야 하기 때문에 text?:string으로 정의했지만 text props를 전달해주지 않을 때 기본적으로 text= 'im here'이 랜더링 되도록 설정했다.

5.전달받은 props의 값을 해당 컴포넌트에서 스타일드 컴포넌트로 사용하고 싶을 때

형식에 주의하자!

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};
`;

6.state 타입 정의

마찬가지로 형식에 주의하자!

const [value, setValue] = useState<string>('');

setValue('hi') // true
setValue(true) // error

기본적으로 타입 추론을 하기때문에 타입 표기를 안해줘도 에러는 발생하지 않지만 가독성 및 협업을 위해서 표기해주는게 좋다.

form 태그 사용법

//App.tsx

function App() {
  const [value, setValue] = useState<string>('');

  const onChange = (event: React.FormEvent<HTMLInputElement>) => {
    const {
      currentTarget: { value },
    } = event;

    setValue(value);
  };

  const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    console.log('hello', value);
  };

  return (
    <div>
      <form onSubmit={onSubmit}>
        <input
          value={value}
          onChange={onChange}
          type='text'
          placeholder='username'
        />
        <button>Log in</button>
      </form>
    </div>
  );
}

export default App;

특별히 다른점은
form에서 발생하는 event에 대한 타입을 정의해줘야한다.
외우지말고 그때그때 구글링해서 찾아보는게 빠름

theme 사용

저번에 포스팅한 theme를 컴포넌트에서 사용하는 방법

const Theme = styled.div`
  background-color: ${(props) => props.theme.bgColor};
  color: ${(props) => props.theme.textColor};
  border: 1px solid ${(props) => props.theme.btnColor};
`;

당연하게도 자동완성 기능을 제공해준다.
props.theme 까지만 코드쳐도 theme에서 설정한 값들의 목록을 보여준다.

profile
프론트엔드 개발 지망생입니다.

0개의 댓글