본문 바로가기

개발

TypeScript와 React.FC

 

React.FC는 React.FunctionComponent의 약자로, 함수형 컴포넌트를 정의할 때 사용하는 타입이다.

이 타입은 컴포넌트의 props 타입을 지정하고, 기본적으로 children prop을 포함한다.

import React from 'react';

interface NavBarProps {
    isOpen: boolean;
    toggleDropdown: () => void;
}

const NavBar: React.FC<NavBarProps> = ({ isOpen, toggleDropdown }) => {
    return (
        <div>
            ...
        </div>
    );
};

export default NavBar;

 

요런 느낌쓰.

 

React.FC를 꼭 쓰지 않아도 되고, 안 쓴 예를 보면 React.FC를 더 잘 이해할 수 있다.

import React, { ReactNode } from 'react';

interface NavBarProps {
    isOpen: boolean;
    toggleDropdown: () => void;
    children?: ReactNode; // 명시적으로 children prop 추가
}

const NavBar = ({ isOpen, toggleDropdown, children }: NavBarProps) => {
    return (
        <div>
            ...
            {children}
        </div>
    );
};

export default NavBar;

 

위에서처럼

children 넘길 때

children: React.ReactNode;

이렇게 정의해주면 됨

 

다른 예를 보면

...props 같이 넘겨주고

<div {...props}> 써준 경우도 있다.

 

 

이것저것 찾아보니까 React.FC 사용을 지양하자는 움직임도 보인다.

https://github.com/facebook/create-react-app/pull/8177

 

Remove React.FC from Typescript template by Retsam · Pull Request #8177 · facebook/create-react-app

This removes React.FC from the base template for a Typescript project. Long explanation for a small change: React.FC is unnecessary: it provides next to no benefits and has a few downsides. (See b...

github.com

 

 

 

'개발' 카테고리의 다른 글

CSS Animatable Properties  (0) 2024.07.08
React Animate Presence  (0) 2024.07.07
Web Accessibility  (0) 2024.07.04
상태(state)와 속성(props)  (1) 2024.06.07
10 React Hooks  (0) 2024.05.26