React.createElement()

shelly·2021년 8월 27일
0

React

목록 보기
8/10

기능


  • 새로운 element를 생성할 때 사용한다.

사용 방법


React.createElement(
  type,
  [props],
  [...children]
)
  • type
    어떤 type의 element를 생성할지 정한다.
    ex) html 태그 "h1" "p" "div" ...
    ex) React 컴포넌트 타입
    ex) ReactFrgment 타입
  • props (optional)
    element의 여러 attributes를 설정할 수 있다.
    ex) className, children
  • children
    • 생성하는 element의 children element를 지정한다.
    • props의 children과 동일한 기능이다.
    • props의 children과 세 번째 인자 children 둘 다 값이 입력될 경우, 세 번째 인자 children에 들어온 값이 적용된다.

사용 예시


  1. props와 children
// props 사용
const elementA = React.createElement("h1", {
  children: "Hello World!" 
})

// children 사용
const elementB = React.createElement("h1", null, "Hello World!")

  • elementA와 elementB의 출력값이 동일하다.
  1. 배열 children
//props 사용
const elementA = React.createElement("h1", {
  children: ["Hello World!", "I'm Shelly"] 
})

// children 사용
const elementB = React.createElement("h1", null, ["Hello World!", "I'm Shelly"] )

  • children은 배열이 될 수 있다.

VanillaJS vs React


in VanillaJS

const element = document.createElement("h1")
element.textContents("Hello World!")

in React

const element = React.createElement("h1", {
  children: "Hello World!" 
})

기타


매번 React.createElement("h1", 어쩌구 저쩌구)를 작성하는게 귀찮다🥲 그런데 JSX라는 문법을 사용하면, 비교적 빠르게 element를 생성하는 코드를 작성할 수 있다.

in React

const element = React.createElement("h1", {
  children: "Hello World!" 
})

in JSX

const element = <h1>Hello World!</h1>;

0개의 댓글