리액트 공식 홈페이지에서는 Element를 다음과같이 정의하고있다.
Elements are the smallest building blocks of React apps.
Element는 리액트 앱의 가장 작은 블록들이라는 것이다.
리액트 Elements는 자바스크립트 객체 형태로 존재한다.
아래 코드는 버튼을 나타내기 위한 Element 코드이다.
{
type: 'button'
props: {
className: 'bg-green',
children: {
type: 'b',
props: {
children: 'Hello, element!'
}
}
}
}
위의 코드가 실제로 렌더링될 때 DOM 코드이다.
<button class='bg-green'>
<b>
Hello, element!
</b>
</button>
타입에 문자열이 아닌, 리액트 컴포넌트를 넣을 수 있다.
{
type: Button,
props: {
color: 'green',
children: 'Hello, element!'
}
}
구체적인 예시를 하나 들어보겠다.
function Button(props) {
return (
<button className={`bg-${props.color}'>
<b>
{props.children}
</b>
</button>
)
}
function ConfirmDialog(props) {
return (
<div>
<p>내용을 확인하셨으면 확인 버튼을 눌러주세요.</p>
<Button color='green'>확인</Button>
</div>
)
}
위 코드를 보면 ConfirmDialog 컴포넌트가 Button 컴포넌트를 포함하고있다.
여기서 ConfirmDialog의 Element는 어떤 형태가 될까?
{
type: 'div',
props: {
children: [
{
type: 'p',
props: {
children: '내용을 확인하셨으면 확인 버튼을 눌러주세요.'
}
},
{
type: Button,
props: {
color: 'green',
children: '확인'
}
}
]
}
}
두번째 children의 타입은 html 태그가 아니라 리액트 컴포넌트의 이름인 Button이다. 이 경우에 리액트는 Button 컴포넌트의 Element를 생성해서 합치게된다. 그래서 최종적으로 Element는 아래와 같은 모습이 된다.
{
type: 'div',
props: {
children: [
{
type: 'p',
props: {
children: '내용을 확인하셨으면 확인 버튼을 눌러주세요.'
}
},
{
type: 'button',
props: {
className: 'bg-green',
children: {
type: 'b',
props: {
children: '확인'
}
}
}
}
]
}
}
이처럼 컴포넌트 렌더링을 위해서 모든 컴포넌트가 createElement 함수를 통해 Element로 변환된다는것을 기억해야한다!
리액트 Element의 중요한 특징
불변성 - Element 생성 후에는 children이나 attributes를 바꿀 수 없다!
아니 화면은 계속 바뀌는데 바꿀 수 없다니...? 아래의 코드를 보자.
function tick() {
const element = (
<div>
<h1>안녕, 리액트!</h1>
<h2>현재 시간 : {new Date().toLocaleTimeString()}</h2>
</div>
);
ReactDOM.render(element, document.getElementById('root'));
}
setInterval(tick, 1000);
tick함수는 현재시간을 포함하여, root div에 렌더링하는 역할을 수행한다. 그리고 자바스크립트의 setInterval함수를 사용해서, 매초마다 tick 함수를 호출하고있다. 이 코드를 실행하면 매초마다 화면에 새로운 시간이 나오게 될 것이다.
내부적으로는, tick 함수가 호출될때마다 기존 Element를 변경하는것이 아니라, 새로운 Element를 생성해서 바꿔치기하는 것이다.
리액트 Element의 불변성 때문에 Element를 업데이트하기 위해서는 새로 만들어야 한다는 중요한 사실!!
'React' 카테고리의 다른 글
React - Component 와 props (0) | 2024.04.28 |
---|---|
JSX 란? (0) | 2024.04.28 |
React 소개와 간단한 연동 (0) | 2024.04.23 |