children의 요소들을 각각 다르게 노출한다거나 sort, filter, slice 같은 조작을 할 때 필요하다.
1. React.Children.toArray()
공식문서
Returns thechildren
opaque data structure as a flat array with keys assigned to each child.
첫 번째 기능
children을 1차원 배열(flat array)로 변환해서 리턴한다. (평탄화)
children이 배열이 아닌 opaque data structure일 때도 동작한다.
※ 구체적인 데이터 구조가 인터페이스에 정의되지 않은 데이터 유형 (undefined 등)
예제1
console.log(children)
console.log(React.Children.toArray(children))
예제2
예제3
두 번째 기능
1차원 배열로 변환하는 과정에서 재조정(Reconciliation)과 렌더링 최적화를 위해
고유한 key 값을 부여한다.
console.log(children)
의 childconsole.log(Children.toArray(children))
의 childReact.Children.toArray()
는children
을 평평하게(Flatten) 만들 때, 중첩된 배열들의 의미를 보존하기 위하여key
를 변경합니다. 즉,toArray
는 반환되는 배열에key
값을 덧붙여서 각 엘리먼트가 갖는key
가 평평해진 배열 내에서만 유효한 범위를 형성하도록 해줍니다.
주의
React.Children.toArray는 <React.Fragment>의 내부를 평탄화하지 않는다.
react-keyed-flatten-children을 사용할 수 있다.
2. React.Children.count()
children에 포함된 컴포넌트의 개수를 반환한다.
3. React.Children.only()
children이 단 하나의 자식(React 엘리먼트)를 갖는지 확인하고 해당 자식 엘리먼트를 반환한다.
그렇지 않을 경우 오류를 발생시킨다.