반응형
JSX문법에서 단일 root 태그로 래핑해야 하는 이유
공식문서에는 이렇게 나온다
JSX는 HTML처럼 보이지만 내부적으로는 일반 JavaScript 객체로 변환됩니다.
두 객체를 배열로 래핑하지 않고는 함수에서 두 객체를 반환할 수 없습니다.
이는 두 개의 JSX 태그를 다른 태그나 Fragment로 래핑하지 않고는 반환할 수 없는 이유를 설명합니다.
잘 이해가 안가서 chatGPT한테 물어봤다.
function MyComponent() {
return (
<div>
<div><span>jj</span></div>
<div><img /></div>
<div>hhhi</div>
</div>
);
}
위 JSX 코드가 JS 객체로 변환되면 다음과 같다.
{
type: 'div',
props: {
children: [
{
type: 'div',
props: {
children: [
{
type: 'span',
props: {
children: 'jj'
}
}
]
}
},
{
type: 'div',
props: {
children: [
{
type: 'img',
props: {}
}
]
}
},
{
type: 'div',
props: {
children: 'hhhi'
}
}
]
}
}
그러니까 래핑하는 태그 1개당 children[]을 만드는 것인데, 래핑하는 최상위 태그가 없다면, 두개의 객체를 배열로 래핑하지 않고 리턴하는 것이다. 예를들면 아래 코드의 리턴과 같다.
function convertedJsxToJs() {
const componentTree1 = {
type: 'div',
props: {
children: 'First element'
}
},
const componentTree2 = {
type: 'div',
props: {
children: 'Second element'
}
};
return componentTree1, componentTree2; // 이것은 componentTree2 반환한다.
}
그래서 최상단에 마지막 래핑 태그로 감싸주어서 다음과 같이 만들어주여야 한다.
function convertedJsxToJs() {
const componentTree1 = [{
type: 'div',
props: {
children: 'First element'
}
},
const componentTree2 = {
type: 'div',
props: {
children: 'Second element'
}
};
const componentTree = [componentTree1, componentTree2]
return componentTree; // 이것은 componentTree1, componentTree2 둘 다 반환한다.
}
반응형
'개발 > React' 카테고리의 다른 글
state 업데이트는 비동기라기보다는 스냅샷이다. (1) | 2024.01.07 |
---|---|
zustand에서 functional update가 가능한 setState만들기 (0) | 2023.11.06 |
react hook life cycle (0) | 2023.10.14 |
useState와 클로저 (0) | 2023.09.13 |
React 18 - useDeferredValue를 이용한 Concurrent Mode 확인 (0) | 2023.08.03 |