본문 바로가기
IT/react

[React] children 잘 활용하기

by 내일은교양왕 2024. 2. 6.

React.Children.toArray()

 

특징 1

불투명 데이터 구조를 각 자식에 할당된 키가 있는 flat arrary로 반환

children을 전달하기 전에 sort 또는 slice하려는 경우 유용

function Box({ children }) {
  console.log(children);
  console.log(React.Children.toArray(children));
  return children;
}

const fruits = [
  { id: 1, name: "apple" },
  { id: 2, name: "kiwi" },
];

export default function App() {
  return (
    <Box>
      <div name="banana">banana</div>
      {fruits.map(fruit => (
        <div key={`${fruit.id}_${fruit.name}`} name={fruit.name}>
          {fruit.name}
        </div>
      ))}
    </Box>
  );
}

 

콘솔 결과

// children
[
  Object1, // banana
  [
    Object2, // apple
    Object3, // kiwi
  ],
];

// toArray
[
  Object1, // banana
  Object2, // apple
  Object3, // kiwi
];

 

 

아래의 코드로 실행하면 3개 (banana, apple, kiwi)가 다 노출

nested array이기에 총 2개가 전부임

function Box({ children }) {
  return children.slice(0,2);
}

 

두개만 보여주고 싶다면, toArray를 사용해서 flat하게 만든 후 slice

function Box({ children }) {
  return React.Children.toArray(children).slice(0, 2);
}

 

특징 2

flat array로 변환하는 과정에서 재조정과 렌더링 최적화를 위해 고유한 key값을 부여

// console.log(children)
{
  key: null,
  props: {
    name: "banana",
    children: "banana"
  }
}

// console.log(Children.toArray(children))
{
  key: "0.0"
  ...
}

 

하지만, Fragment안에 있는 값들은 키 값이 붇지 않고, fragment 자체가 키 값이 붙는다.

 

https://fe-developers.kakaoent.com/2021/211022-react-children-tip/