[TypeScript & React] #0 시작하기

1Hoit·2023년 6월 3일

TypeScript & React

목록 보기
1/5
post-thumbnail

시작에 앞서

기본적인 내용을 잠시 다뤄보려고 한다.
타입스크립트에 대한 정말 기본적인 내용만 앞서 다뤘으므로 전혀 내용을 모른다면 이전 포스팅 을 참고하고 시작하길 바란다.


1. react + typescript 프로젝트 생성

npx create-react-app [프로젝트 이름] --template typescript

2. 함수형 컴포넌트 작성 방법

type Imgage , interface ListProps 와 같이
컴포넌트의 props 타입을 명시하여 작성해준다.
만약 property로 유효하지 않은 값이 전달되면 오류를 확인할 수 있다!

import React from "react"

type = Image = {
  src: string;
}

interface ListProps {
  header: string;
  content: string;
  image: Image;
}

const List = ({header, content, image}: ListProps) =>{
  return(
    <div>
      {image && <img src={image.src}>}
      <header>{header}</header>
      <p>{content}</p>
    </div>
  );
};

3. Hook 사용법

useState

초기값을 설정하는 경우라면 자동으로 타입이 지정되므로 명시적으로 타입을 지정할 필요가 없긴하다.
그러나 초기값을 설정할 수 없는 경우 아래와 같이 작성한다.

type ListObj = {
  id:string;
  header: string;
  content: string | null;
  image: string | null;
};

const [list, setList] = useState<ListObj | null>(null);
  • 위처럼 어떤 type의 값이 올지 모르기 때문에 초기값으로 null을 지정해준다.

useEffect : 별도 타입 지정이 필요없다.

4. Event 처리 방법

event의 type으로는 React의 이벤트 시스템을 사용하기 때문에 React 버전의 이벤트를 직접 지정해야한다.

외우지 않아도 된다.
태그의 해당 eventHandler 에 마우스를 올려보면 친절히 VS Code에서 알려주긴 한다.

간단하게 3가지 정도만 확인하자.

  • onChange 이벤트
const handleChange = (e: React.ChangeEvent<HTMLInputElement>)=>{
  event.preventDefault();
  //로직 작성
}

  • onSubmit 이벤트
const handleChange = (e: React.FormEvent<HTMLInputElement>)=>{
  event.preventDefault();
  //로직 작성
}

  • onClick 이벤트
const handleChange = (e: React.MouseEvent<HTMLInputElement>)=>{
  event.preventDefault();
  //로직 작성
}

마치며

기본적인 내용만 일단 찍먹 해보았다.
다음 포스팅부터 직접 작업을 해보며 위에 대한 내용을 복습하며 진행해야겟다!

profile
프론트엔드 개발자를 꿈꾸는 원호잇!

0개의 댓글