본문 바로가기
개발/React

JSX Element React Element ReactNode 차이

by 안뇽! 2024. 1. 8.
반응형

JSX Element, React Element, ReactNode

먼저 JSX가 createElement로 변환되는 것을 한번 보자

return <div>hi</div>;

 

위 JSX 코드는 다음과 같이 변환된다.

return React.createElement('div', null, 'hi');

 

JSX Element와 React Element의 관계

JSX문법으로 적는 return <div>hi</div>는 react와 컴파일러에 의해 JS인 createElement로 변환된다.

이 createElement를 통해 생성되는 element가 바로 가상돔의 표현방식인 React Element이다.

 

실제로 타입을 보았을때는 JSX Element가 React Element보다 조금 더 유연한 방식이다 정도로만 느껴진다.

 

이 타입은 React Element의 타입인데 매개변수의 타입이 명시되어 있다.

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

 

한편, JSX Element는 React Element의 제너릭에 any를 넣어준것이다.

 

그러니 JSX Element와 React Element의 관계를 정리하면

  1. 우리가 Sugar 문법으로 JSX Element 를 작성한다.
  2. JSX는 react와 컴파일러에 의해 JS인 createElement로 변환되는데 createElement를 통해 생성되는 element가 React Element이다.
  3. 이 React Element는 가상돔의 표현방식이다.

ReactNode

그럼, ReactNode는 뭘까?

컴포넌트의 children에는 element, string, null, React.Fragment 등등 여러가지가 올 수 있는데 이 children의 type이 ReactNode이다.

interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES {}

type ReactNode =
        | ReactElement
        | string
        | number
        | Iterable<ReactNode>
        | ReactPortal
        | boolean
        | null
        | undefined
        // 이건뭐지ㅣ... ㅋㅋㅋ
        | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES[
            keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES
        ];

 

반응형