프로그래밍/React

React Clone element

수박수박좋다 2022. 2. 1. 13:31
반응형

cloneElement()

React.cloneElement(
  element,
  [config],
  [...children]
)
  • 새로운 element를 복사하여 반환하는 func
  • config는 key, ref를 포함한 모든 props를 담음
  • 결과 element는 원본 element의 prop과 새로 추가된 props을 합친 요소다
  • 새로운 children역시 기존 children을 대체하는 새로운 요소가 된다
  • 원본의 key, ref는 config에 새로운 prop이 없다면 유지된다.
import React from "react";
import "./styles.css";

const Parent = ({ children, anotherProps }) => {
  const parentsVar = "Tired";
  return (
    <div>
      I'm Parent
      {React.cloneElement(children, { parentsVar, anotherProps })}
    </div>
  );
};

const Child = ({ name, parentsVar, anotherProps }) => {
  return (
    <div>
      I'm child, name is {name} {parentsVar} {anotherProps}
    </div>
  );
};

export default function App() {
  return (
    <div className="App">
      <Parent anotherProps="직접 내려주기">
        <Child name="smile" />
      </Parent>
    </div>
  );
}
  • Parent에서 props로 받는 children element에 새로운 props을 추가하여 렌더링할 수 있다.
  • 자식에서 주는 것 외에 부모컴포넌트 내부에서 만든 props, 아니면 그 부모 컴포넌트를 랜더링하는 상위에서 prop을 따로 줄 수 있다.
  • children에 대해서 cloneElement를 통해 새로운 prop을 만들어 전달함에 따라 재사용성을 높일 수 있다.
반응형