«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
Recent Posts
Recent Comments
관리 메뉴

뉴히의 개발 로그

[TIL] 20230731 - React typeScript props 내려주기 props 타입 본문

개발일지/TIL

[TIL] 20230731 - React typeScript props 내려주기 props 타입

뉴히 2023. 7. 31. 23:21

상위 컴포넌트에서 useState 함수를 넘길 때 마우스를 올리면 내려줘야할 적절한 타입을 제공해준다.

그럼 그대로 내려주면됨

깐깐하고 친절한 타입스크립트 ㅎㅎ

React.Dispatch는 TypeScript에서 제공하는 제네릭(Generic) 타입으로, 상태를 업데이트하는 함수의 타입을 지정할 수 있도록 해준다.

React.SetStateAction<Todo[]>todos 상태를 업데이트하는 데 사용될 수 있는 다양한 값들의 유형을 정의합니다. 일반적으로 이 값은 새로운 상태를 나타내는 배열일 수 있지만, 타입에 따라 다른 값을 전달할 수도 있습니다. 예를 들어, 상태를 비우거나 초기값으로 되돌리기 위해 빈 배열을 전달하거나 이전 상태를 유지하기 위해 setTodos(todos)와 같이 현재 상태를 그대로 전달하는 것도 가능

 

자주 사용하는 경우 가독성을 높이기 위해 유형 별칭을 만들어 사용.

type Dispatcher<S> = Dispatch<SetStateAction<S>>;

const MyChildComponent1 = (
  myVar: boolean,
  setMyVar: Dispatcher<boolean>,
) => {...};

 

그외 더보기 참고링크

https://newbedev.com/passing-usestate-as-props-in-typescript

 

Passing useState as props in typescript

The type that would match the function returned from invoking useState would be: setMyVar: (value: boolean | ((prevVar: boolean) => boolean)) => void; If we loo

newbedev.com

 

그 외 TypeScript 타입 

 

React.FC를 사용하지않는 이유! 참고

https://yceffort.kr/2022/03/dont-use-react-fc

 

 

React.FC<Props>:

FC는 "Functional Component"의 약어로, 함수형 컴포넌트를 정의할 때 사용됩니다. Props는 해당 컴포넌트에 전달되는 프로퍼티(Props)의 타입을 지정

import React from 'react';

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

const MyComponent: React.FC<MyComponentProps> = ({ name, age }) => {
  return (
    <div>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
    </div>
  );
};

 

React.ReactNode:

ReactNode는 리액트 컴포넌트가 반환할 수 있는 모든 유형(컴포넌트, 문자열, 숫자, 배열 등)을 포함하는 TypeScript 타입

const MyComponent: React.ReactNode = () => {
  return (
    <div>
      <p>Hello, World!</p>
    </div>
  );
};

 

React.CSSProperties:

CSSProperties는 리액트 컴포넌트의 style 프로퍼티에 적용할 수 있는 CSS 속성들의 객체 타입

const styles: React.CSSProperties = {
  color: 'blue',
  fontSize: '16px',
  fontWeight: 'bold',
};

const MyComponent: React.FC = () => {
  return <div style={styles}>Styled Text</div>;
};

 

React.HTMLProps<Element>:

HTMLProps는 HTML 요소에 사용되는 기본 프로퍼티들을 포함하는 TypeScript 타입입니다. Element에는 해당 HTML 요소의 태그 이름이 들어감

import React from 'react';

const MyButton: React.FC<React.HTMLProps<HTMLButtonElement>> = (props) => {
  return <button {...props}>Click Me!</button>;
};

 

React.MouseEvent<Element>:

React에서 클릭 이벤트와 관련된 타입을 정의합니다. Element에는 해당 요소의 태그 이름이 들어갑니다

import React from 'react';

interface ButtonProps {
  onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
}

const MyButton: React.FC<ButtonProps> = ({ onClick }) => {
  return <button onClick={onClick}>Click Me!</button>;
};

 

React.ChangeEvent<Element>:

ChangeEvent는 폼 요소(input, select, textarea 등)의 값이 변경되었을 때 발생하는 이벤트 객체의 타입을 나타냅니다. Element에는 해당 폼 요소의 태그 이름이 들어감

import React, { useState } from 'react';

const MyInput: React.FC = () => {
  const [text, setText] = useState('');

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

  return <input type="text" value={text} onChange={handleChange} />;
};

 

추가로 참고할 사이트 Basic prop types examples

https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/basic_type_example/

 

 

팀원분이 공유해주신 꿀팁 !

redux toolkit은 typescript로 만들어진 패키지라 따로 @types 설치 안해도됨!

 

 

npm 들어가보면 타이틀 옆에 TS 아이콘이 들어가있다

 

그리고 추가로 과제진행해야할때 참고할 부분

// app/store.ts

import { configureStore } from '@reduxjs/toolkit'
// ...

const store = configureStore({
  reducer: {
    posts: postsReducer,
    comments: commentsReducer,
    users: usersReducer,
  },
})

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch
// app/hooks.ts

import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
import type { RootState, AppDispatch } from './store'

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch: () => AppDispatch = useDispatch
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector

리덕스 공식문서 참고!

https://react-redux.js.org/using-react-redux/usage-with-typescript