티스토리 뷰

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

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함