React 공식 홈페이지 따라하기
React 만들어보기 (3) - create Element
vitamin3000
2025. 1. 26. 21:40
이번 포스트에서는 지난번에 작성한 vdom를 분리하고 한눈에 알아보기 편하게 하도록 수정하려고 한다
(1) 기존에 작성한 vdom
const vdom = {
tag: 'p',
props: {},
children: [
{
tag: 'h1',
props: {
style: 'color: red'
},
children: ["React 만들기"],
},
{
tag: 'ul',
props: {
//...
위 코드를 살펴보면, 하나의 아이템에 tag, props, children을 element로 갖고 있음을 확인할 수 있고,
children에서는 또 다시 자식 요소로 tag, props children을 갖는다.
이는 dom 객체 같이 최상위 root 노드를 갖는 즉 트리 형태이다.
(2) 따라서 다음과 같이 createEelement 함수를 만들 수 있다.
export function render(vdom, container) {
container.appendChild(createDom(vdom));
}
export function createElement(tag, props, children) {
return { tag, props, children };
}
이때 children은 객체가 아니라 배열 형태임에 주의하라.
따라서 배열 형태로 변환해주어야 한다.
const element = document.createElement(node.tag);
Object.entries(node.props)
.forEach(([name, value]) => element.setAttribute(name, value));
(3) render 함수와 createElement 함수를 호출한다.
render(vdom, document.querySelector('#root'))
const vdom = createElement('p',{},
createElement('h1',{}, "React 만들기"),
createElement('ul',{}, "",
createElement('li',{style: 'color: red'}, "첫번째 아이템"),
createElement('li',{style: 'color: blue'}, "두번째 아이템"),
createElement('li',{style: 'color: green'}, "세번째 아이템")
)
)
또는 다음과 같이 스프레드 연산자를 사용할 수 있다.
const vdom2 = createElement('p',{}, ...children)
(4) 여러분이 보시기에는 어떤게 더 한 눈에 알아보기 편하다고 생각하는가?
사람에 따라 다를 수 있곘지만 나는 분리하는게 유지보수에 용이하다고 생각한다.