React의 Typescript 타입 종류 (2)

eeensu·2023년 10월 22일
0

React 실무

목록 보기
14/22
post-thumbnail

React.PropsWithChildren

PropsWithChildren은 React 라이브러리의 TypeScript 타입 중 하나이다. 이 타입은 컴포넌트의 속성(props)을 정의할 때 사용되며, 해당 컴포넌트가 자식 컴포넌트를 가질 수 있을 때 유용하게 활용된다.

react는 17버전까지는 children 속성을 FC 타입에 포함하여 함수형 컴포넌트의 타이핑을 지원했다. 하지만 18버전 부터는 FC타입에서 children 속성을 제거했다. 그리고 PropsWithChildren 이라는 새로운 제너릭 타입을 제공하여 children?: ReactNode 부분을 대체했다.

PropsWithChildren 의 제너릭 타입으로 안에 기존의 Props를 넣어주면 children prop을 포함하여 컴포넌트를 작성할 수 있다.

import type { FC, PropsWithChildren } from 'react';

interface Props{
    name: string;
    age: number;
}

const Example: FC<PropsWithChildren<Props>> = ({ age, name, children }) => {

    return (
        <div>
        	{children}
        </div>
    );
};

export default Example;





React.ComponentProps

특정 컴포넌트의 속성(props)을 추출하는 데 사용되는 타입이다. 이를 통해 컴포넌트의 prop 타입을 동적으로 가져올 수 있다.

import React from 'react';
import { ComponentProps } from 'react';

// 버튼 컴포넌트 정의
const Button = ({ onClick, children }: { onClick: () => void; children: React.ReactNode }) => (
  <button onClick={onClick}>{children}</button>
);

// Button 컴포넌트의 Props 타입 사용
type ButtonProps = ComponentProps<typeof Button>;

// ButtonProps를 사용하는 다른 컴포넌트 또는 함수
const logButtonProps = (props: ButtonProps) => {
  console.log(props);
};

export default Button;





React.CSSProperties

CSS 속성을 정의하는 타입으로, 스타일 객체를 만들 때 사용된다. 이 타입을 지정해주면 객체 안에서 css 속성을 사용할 수 있게 해준다.

import { CSSProperties } from 'react';

const myStyle: CSSProperties = {
  color: 'blue',
  fontSize: '16px',
};

const MyComponent: FC = () => {
  return <div style={myStyle}>Styled text</div>;
};





React.ChangeEvent<T>

폼 요소의 값이 변경될 때 발생하는 이벤트의 타입을 정의한다. 주로 사용자 입력에 응답하여 폼 요소의 값이 변경될 때 발생하는 이벤트 객체이며 input 엘리먼트에 사용한다. 제너릭으로 해당 ChangeEvent가 발생하는 HTMLElement 타입을 넣어 적용하면 된다. 주로 change 이벤트가 자주 일어나는 HTMLInputElement 타입이 유용하게 사용된다.

import React, { useState } from 'react';

const InputComponent: FC = () => {>('');
  const [inputValue, setInputValue] = useState<string>('');

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  return (
    <div>
      <input
        type="text"
        value={inputValue}
        onChange={handleInputChange}
      />
      <p>value: {inputValue}</p>
    </div>
  );
};





React.DetailedHTMLProps

HTML 요소를 사용할 때, 해당 요소의 속성(props)을 지정할 때 HTML 요소의 특정 속성에 대한 타입 정보를 필요로 한다. React.DetailedHTMLProps는 이러한 요소의 속성에 대한 타입 정보를 제공하는 역할을 한다.

import { InputHTMLAttributes, DetailedHTMLProps } from 'react';

type Props = DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>
profile
안녕하세요! 26살 프론트엔드 개발자입니다! (2024/03 ~)

0개의 댓글