어떤 컴포넌트에서 아래와 같이 return을 한다면 어떻게 될까?
return (
<h2>Hi there!</h2>
<p>This does not work :-(</p>
);
아래처럼 두 개 이상은 return할 수 없다는 에러가 출력된다.
You can't return more than one "root" JSX element.
왜냐하면 자바스크립트에서는 두 개 이상을 리턴할 수 없기 때문이다.
위의 코드를 createElement메서드를 사용해 바꿔보면 더 이해하기 쉽다.
return (
React.createElement('h2', {}, 'Hi there!')
React.createElement('p', {}, 'This does not work :-(')
);
이와 같이 자바스크립트에서는 두 개 이상을 리턴할 수 없기 때문에 우리는 요소들을 하나의 태그로 감싸거나 의미없는 태그의 사용을 피하기 위해 React Fragment를 사용하는 것이다.
따라서 아래와 같이 여러 방식으로 코드를 수정할 수 있다.
return (
<div>
<h2>Hi there!</h2>
<p>This work :-)</p>
</div>
);
return (
<React.Fragment>
<h2>Hi there!</h2>
<p>This work :-)</p>
</React.Fragment>
);
return (
<>
<h2>Hi there!</h2>
<p>This work :-)</p>
</>
);