React.createElement 이해하기

김동현·2023년 8월 7일
0

타입 정의

여러 버전의 React.createElement 함수가 오버로딩 되어 타입 정의되어 있다.
그 중 제일 일반적인 정의를 가지고 왔다.

function createElement<P extends {}>(
  type: FunctionComponent<P> | ComponentClass<P> | string,
   props?: Attributes & P | null,
   ...children: ReactNode[]): ReactElement<P>;

type , props , children 을 매개변수로 받는다.

  • type : (함수형 컴포넌트 | 클래스 컴포넌트 | 문자열) 중 하나를 전달받는다.
  • props : 선택적 매개변수이며 미리 정의되어있는 Attributes 타입과 호출할때 주어지는 타입 매개변수인 P 와의 교차 타입이다.
  • children : 나머지 매개변수이기 때문에 인수를 넘겨주지 않아도 기본적으로 빈 배열을 갖기때문에 선택적 매개변수이다.
    인수로 전달하려면 ReactNode 타입이 담겨있는 배열을 전달해야 한다.

리액트로 구현

import React from 'react'
const CE = React.createElement

const VirtualDOM = CE('ul', null, [
  CE('li', null, [
    CE('a', {href: 'https://www.google.com', target: '_blank'}, [
      CE('p', null, '구글로 이동')
    ])
  ])
])
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement)
root.render(VirtualDOM)

호출이 복잡하다.
리액트 팀은 이러한 복잡성을 해결하고자 JSX기능을 언어 확장 형태로 추가했다.

JSX 버전

const JSXVirtualDOM = (
  <ul>
    <li>
      <a href="https://www.google.com" target="_blank">
        <p>구글로 이동</p>
      </a>
    </li>
  </ul>
)
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement)
root.render(VirtualDOM)
profile
프론트에_가까운_풀스택_개발자

0개의 댓글