티스토리 뷰
React에서 컴포넌트가 여러 element를 반환하는 것은 흔한 패턴이다
Fragment는 DOM에 별도의 Node를 추가하지 않고, 여러 자식을 그룹화할 수 있다.
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
);
다음과 같은 컴포넌트가 있다.
class Table extends React.Component {
render() {
return (
<table>
<tr>
<Columns />
</tr>
</table>
);
}
}
위의 컴포넌트가 유효하려면 Columns 컴포넌트는 td 엘리먼트만 반환해야 된다.
Columns 컴포넌트가 div로 감싸져 있다면 이는 잘못된 html이 된다.
<table>
<tr>
<div> // tr태그 아래에 div태그가 있으면 안된다.
<td>Hello</td>
<td>World</td>
</div>
</tr>
</table>
이러한 오류상황을 해결하기 위해 Fragments를 이용할 수 있다.
Columns 컴포넌트를 React.Fragment로 감싸는 것이다.
class Columns extends React.Component {
render() {
return (
<React.Fragment> //div가 아닌 React.Fragment로 감싸준다.
<td>Hello</td>
<td>World</td>
</React.Fragment>
);
}
//html출력 결과
<table>
<tr>
<td>Hello</td>
<td>World</td>
</tr>
</table>
빈 태그를 감싸는 것도 같은 의미이다.
class Columns extends React.Component {
render() {
return (
<>
<td>Hello</td>
<td>World</td>
</>
);
}
}
Fragments에 key가 있을 경우(map과 같이 배열로 매핑해야 될 경우) React.Fragment를 명시적으로 작성하여야 한다.
{props.items.map(item => (
<React.Fragment key={item.id}>
<dt>{item.option1}</dt>
<dd>{item.option2}</dd>
</React.Fragment>
))}
key는 Fragment에 전달할 수 있는 유일한 attribute이다.
추후 event handler와 같은 추가적인 attribute를 지원할 수도 있다.
참고 : ko.reactjs.org/docs/fragments.html
Fragments – React
A JavaScript library for building user interfaces
ko.reactjs.org
'front-end > react' 카테고리의 다른 글
[React공식문서읽기] JSX이해하기 (0) | 2021.04.22 |
---|---|
[React공식문서읽기] 고차 컴포넌트(HOC, Higher Order Component) (0) | 2021.04.21 |
[React공식문서읽기] Ref전달 (0) | 2021.04.17 |
[React공식문서읽기] Error Boundaries (0) | 2021.04.17 |
[React공식문서 읽기] Context (0) | 2021.04.17 |