React

[React] JSX.Element vs ReactNode vs ReactElement

uni_i 2022. 10. 8. 21:11

1. 전반적인 구조

ts에서 주로 children component를 props를 넘길때, 자주 사용하는 type 종류와 차이에 대해 알아보겠다.

자주 사용했던, JSX.Element, ReactNode, ReactElement가 있는데 이들의 관계는 간단하게 아래 사진과 같다. 

 

[사전 지식]

1) 클래스형 컴포넌트는 render 메소드에서 ReactNode를 리턴

 

2) 함수형 컴포넌트는 ReactElement를 리턴

 

3) jsx로 작성된 코드를 babel을 통해 자바스크립트로 변환을 하면, React.createElement()로 나타낸다.
변환 전)

const example = () => {
  return <div>hello, world</div>
}

변환 후)

const example = () => {
  return /*#__PURE__*/React.createElement("div", null, "hello, world");
};
// type, key, props

이때, React.createElement로 반환되는 타입이 ReactElement와 JSX.Element이다.

 

 

2. ReactNode

type ReactNode = ReactElement | string | number | ReactFragment | ReactPortal | boolean | null | undefined;
  • ReactNode는 render() 메소드를 통해서 반환되는 값이며, render()를 사용하는 class component의 반환값은 ReactNode인 것이다.
  • ReactNode는 위의 코드에서 알 수 있듯 ReactElement와 함께, string, number, boolean, null, undefined 등 자바스크립트 내에서 모든 요소의 타입을 포함하고 있다. 그렇기 때문에, 어떤 props가 올지 모를경우, ReactNode로 지정하면 좋다

 

 

3. ReactElement

interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>> {
    type: T;
    props: P;
    key: Key | null;
}
  • 함수형 컴포넌트는 ReactElement를 반환한다.
  • type, props를 가지는 타입.

 

4. JSX.Element

declare global {
    namespace JSX {
        interface Element extends React.ReactElement<any, any> { }
		...
	}
}
  • JSX.Element는 ReactElement의 props와 type이 둘다 any로, ReactElement에 any로 제네릭한 형태로 보면 된다.