본문 바로가기

React/TS7

TS에서 ForwardedRef 사용하기 간혹 컴포넌트에서 사용하는 ref를 외부에 노출시켜야 하는 경우가 있다. 이런 경우 다음과 같이 사용할 수 있다. interface ITestComponentProps { name: string; } const TestComponent = forwardRef(function TestComponent(props: ITestComponentProps, ref: ForwardedRef) { return ( {props.name} ) }) export default TestComponent 하지만 ref를 제공하는 컴포넌트에서 해당 ref를 사용한 로직을 작성하려고 할 때 타입에러가 발생할 수 있다. interface ITestComponentProps { name: string; } const TestComp.. 2023. 7. 30.
React에서 TypeScript 사용하기 - Redux Middleware(Thunk, Saga) 비동기 작업을 처리할 때 주로 redux middleware를 사용하게 됩니다. 이때 주로 사용하는 library는 redux-thunk와 redux-saga입니다. 그래서 이번 글에서는 두 개의 library를 TS로 어떻게 사용하면 될지 소개합니다. Tip. 비동기 요청을 통해 가져오는 데이터의 경우 직접 타입을 하나 하나 정해주기 어려운 경우가 있습니다. 그럴 때 데이터를 넣어주면 자동으로 타입으로 변환해주는 서비스를 이용하면 편하게 타입을 만들 수 있습니다. ex. { "id": 1, "text": "this is text", "done": false } => export interface Todo{ id: number; text: string; done: boolean; } quicktype.i.. 2020. 10. 28.
React에서 TypeScript 사용하기 - Redux with typesafe-actions TS 사용하지 않고 redux module 코드를 작성할 때는 유틸 함수인 redux-actions 라이브러리를 사용했습니다. action creator나 reducer를 작성할 때 코드의 가독성을 올려줄 뿐만 아니라 코드를 작성하기 편리했습니다. typesafe-actions도 이러한 유틸 라이브러리인데 TS를 지원해줍니다. 먼저 redux-actions를 사용한 redux module의 코드는 다음과 같습니다. import { createAction, handleActions } from "redux-actions" const INCREASE = "counter/INCREASE" const DECREASE = "counter/DECREASE" export const increase = createAc.. 2020. 10. 26.
React에서 TypeScript 사용하기 - Redux TypeScript는 필수 요소가 아니기 때문에 라이버러리를 쓸 때 Type을 지원해줄 수도 있고 안해줄 수도 있습니다. 공식적으로 지원해주는 경우도 있지만 3rd party library형식으로 커뮤니티에서 지원해주는 경우가 있는데 이럴 때 다음 사이트에서 쉽게 확인이 가능합니다. www.typescriptlang.org/dt/search?search=react-redux Search for typed packages Find npm packages that have type declarations, either bundled or on Definitely Typed. www.typescriptlang.org Redux Module Ducks 패턴 ducks 패턴은 redux module을 작성할 때 .. 2020. 10. 26.