리액트의 Element (Rendering Elements)

5o_hyun·2022년 12월 20일
0
post-thumbnail

Elements란?

리액트를 구성하는 가장 작은 블록단위, 화면에 표시할 내용을 기술한다.

리액트 element와 DOM element는 다른개념임을 주의하자!!

  • 브라우저DOM에 있는 html요소가 element
  • 리액트 virtualDOM에있는 요소가 react element

Elements의 생김새

리액트 elements는 자바스크립트 객체 형태로 존재한다.

type: Button,
props:{
	class : 'green',
    children : 'hello world'
}

// 실제로 어떻게 쓰이는지 알아보자
function Button(props){
	return(
      <button className={`bg-${props.color}`}>
        <b>{props.children}</b>
      </button>
    )
}

function Confirm(props){
	return(
      <div>
        <p>확인하셨으면 버튼누르기</p>
        <Button color="green">확인</Button>
      </div>
    )
}

Button컴포넌트를 가지고있는 Confirm의 element는 어떤모습일까?

{
  type : `div`,
  props : {
  	children :[
      {
        type: `p`,
        props: {
        	children:`확인하셨으면 버튼누르기`
        }
      },
      {
        type : `button`,
        props : {
          color: `bg-green`,
          children:{
          	type:`b`,
            children:`확인`
          }
        }
      }
 /*     {
        type : Button,
        props : {
          color: `green`,
          children:`확인`
        }
      } */
    ]
  }

}

ConfirmButton의 컴포넌트를 가지고 있으므로 최종적으로는 Button 컴포넌트로 자바스크립트로 변환되어 다음과 같은 형태로 읽히게된다.

Elements 특징

1. 변경할수없다. 불변성

한번 생성된 elements는 변하지않는다. elements생성후에는 children이라 attributes를 바꿀수없다.
붕어빵틀(component)에 반죽을넣고 시간이 지나면 붕어빵(element)이 구워져나오는데 시간이지나면 이미구워진 붕어빵속을 바꿀수는 없다.

그럼 화면에 변경된 element를 보여주기 위해서는 어떻게 해야할까?

기존 element를 변경하는것이아니라 새로운 element를 만들어서 바뀔부분을 기존element로 바꾼다.

Elements 렌더링하기

<div id="root"></div> // Root DOM Node : react의 최상단에 단 한개를 갖는다.
// element를 root DOM Node에 렌더링
const element = <h1>hello</h1>;
ReactDOM.render(element, document.getElementById('root'));
profile
학생 점심 좀 차려

0개의 댓글