본문 바로가기
IT/문제 해결 기록

React component props에 typescript 일부 적용하기(history, setState, withRouter)

by 겨발자 2022. 4. 30.

토이 프로젝트에서 React component의 props에 typeScript를 적용하면서 생기게 된 사항들을 정리해 보았다.

 

1. history props type 정의

페이지 이동을 위해 history 객체를 props로 받아 push 메소드를 사용했는데, props에 이 history 객체에 대한 type을 정의하는 방법을 몰라 찾아보았다. 검색으로 찾아 본 내용으로는 react-router-dom 패키지에서 RouteComponentProps를 가져와 선언하면 되는 형태였다. RouteComponentProps의 정의된 interface 형태는 아래와 같다.

export interface RouteComponentProps<
    Params extends { [K in keyof Params]?: string } = {},
    C extends StaticContext = StaticContext,
    S = H.LocationState
> {
    history: H.History<S>;
    location: H.Location<S>;
    match: match<Params>;
    staticContext?: C | undefined;
}

 

본인은 history 객체만 사용하므로 RouteComponentProps의 history에만 접근해 인터페이스를 선언해 주었다.

interface Props {
  history: RouteComponentProps["history"];
}

출처

https://stackoverflow.com/questions/49342390/typescript-how-to-add-type-check-for-history-object-in-react

 

Typescript: How to add type check for history object in React?

I have the following piece of code, which receives a history object as prop: const ChildComponent = ({ history }) => ( <div className={styles.body}> <div className={...

stackoverflow.com

 

2.  state 정의 함수(setState) props type 정의

상위 컴포넌트로부터 state를 정의하는 함수를 props로 내려 받았을 때 type을 정의하는 내용도 찾아보았다. 이 경우에서는 아래와 같이 type을 정의하였다.

 

import { Dispatch, SetStateAction } from "react";

interface Props {
  setToggle: Dispatch<SetStateAction<boolean>>;
  toggle: boolean;
}

react 라이브러리에서 Dispatch, SetStateAction를 import하고 Dispatch<SetStateAction<T>>와 같은 형태로 type을 선언하면 해결이 가능하다. 찾아보니까 state를 정의하는 함수로 props로 받는 경우가 많은 경우 위 타입 구문을 따로 module로 작성해서 가져오는 형태로도 활용을 하는 것 같다.

 

출처

https://stackoverflow.com/questions/56028635/passing-usestate-as-props-in-typescript

 

Passing useState as props in typescript

Say I have a parent component with two child components: const Parent = () => { const [myVar, setmyVar] = useState(false) return ( <> <MyChildComponent1 myVar={myVar}

stackoverflow.com

 

3. props with withRouter

1, 2와 같이 type을 선언하는 과정에서

 

jsx.element' is not assignable to parameter of type 'componenttype<routecomponentprops<any, staticcontext...와 같은 에러가 발생하였다. 라우팅에 있어서 component를 react-router-dom의 withRouter로 감싸주는 형태로 사용하고 있는데, 새로이 선언한 props의 type을 인식하지 못해 발생한 에러 같다. 따라서 선언한 interface가 RouteComponentProps을 extends 하여 해결하였다.

 

import { Dispatch, SetStateAction } from "react";

interface Props extends RouteComponentProps {
  setToggle: Dispatch<SetStateAction<boolean>>;
  toggle: boolean;
}

 

출처

https://stackoverflow.com/questions/70707309/withrouter-error-using-function-component-and-typescript-jsx-element-is-not-ass

 

Withrouter Error using function component and typescript jsx.element' is not assignable to parameter of type routecomponentprops

I am using react typescript with function component. Trying to pass props to sub component named Input.tsx which defined interface for props. While export with withrouter getting this error. Please

stackoverflow.com

 

댓글