[리액트 컴포넌트 타입 비교] ReactNode, ReactElement, JSX.Element

junamee·2022년 4월 5일
0

프론트엔드

목록 보기
11/16

미리 내용을 요약하자면
타입의 범위는 ReactNode(포괄) > ReactElement > JSX.Element 로 나열해볼 수 있다.
클래스 및 children prop의 타입은 ReactNode로 반환되고 일반 함수형 컴포넌트에서는 ReactElement를 반환한다.


ReactElement와 JSX.Element

이 둘은 거의 유사한 대상으로 보면 된다.
함수형 컴포넌트의 리턴값에 해당된다. ReactElement|null

ReactElement

interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>> {
     type: T;
     props: P;
     key: Key | null;
 }

JSX.Element
전역에 정의 되어있고 React.ReactElement에서부터 상속받고 있다.
ReactElemet의 prop과 type이 any인 요소으로 생각하면 된다.

declare global {
	namespace JSX {
 		interface Element extends React.ReactElement<any, any> { }
   ...
  • jsx엘리먼트 ➡️ babel 트렌스파일링

    JSX는 바벨에 의해서 React.createElement(component, props, ...children) 함수로 트랜스파일된다. 첫번째 인자 component에는 ReactComponent, ReactFragment가 올 수 있으며 리액트 엘리먼트를 반환한다. jsx엘리먼트를 사용하는 이유는 번거롭게 React.createElement를 호출하지 않아도 된다는 점에서 사용이 권장된다. (*jsx를 사용하지 않고도 리액트를 사용할 수 있다_JSX없이 사용하는 React)

    • before

      function BasicButton({disabled, onClick, children}) {
        return <button disabled={disabled} onClick={onClick} style={{background:'red', margin:10}}>{children}</button>;
      }  
      
      function DisabledButton(){
        return (<Hello disabled onClick={()=>console.log('click disabled')}>비활성버튼</Hello>)
      }
    • after

      function BasicButton({
        disabled,
        onClick,
        children
      }) {
        return /*#__PURE__*/React.createElement("button", {
          disabled: disabled,
          onClick: onClick,
          style: {
            background: 'red',
            margin: 10
          }
        }, children);
      }
      
      function DisabledButton() {
        return /*#__PURE__*/React.createElement(Hello, {
          disabled: true,
          onClick: () => console.log('click disabled')
        }, "\uBE44\uD65C\uC131\uBC84\uD2BC");
      }

ReactNode

ReactNode는 모든 것을 지칭한다고 볼 수 있다.
string, number, boolean, null, undefined, ReactElement, ReactFragment, ReactPortal

클래스형 render함수의 리턴타입, PropsWithChildren의 children 타입으로 사용된다.
type PropsWithChildren<P> = P & { children?: ReactNode };

type ReactText = string | number;
type ReactChild = ReactElement | ReactText;

interface ReactNodeArray extends ReadonlyArray<ReactNode> {}
type ReactFragment = {} | Iterable<ReactNode>;
type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;
profile
아티클리스트 - bit.ly/3wjIlZJ

0개의 댓글