Web Development/Front

[React] React.cloneElement

alexrider94 2021. 6. 17. 22:11

React.cloneElement() 

- 지정한 Element를 복사해 반환한다. 추가적으로 children과 props를 같이 넘겨줄 수 있어서 필요시에 부모에서의 props를 자식에게 props를 전달해야하는 경우 사용할 수 있다.

 

React.cloneElement(
  element,
  [props],
  [...children]
)

 

사용 예시

 

- Parent.tsx

{React.Children.map(props.children, (child) => {
	if (child) {
    	return React.cloneElement(child as ReactElement, {
        	onDragHandle: provided.dragHandleProps ?? null
        });
    } else {
        return child;
    }
})}

- Drag.tsx

<Parent onDragEnd={handleDragAndDrop} disabled={!enableDagAndDrop}>
	<Children>
		...
   	</Children>
</Parent>

 

-Children.tsx

const Children:FC<ChildrenProps> = ({children:React.ReactNode,onDragHandle:SomeProps}) => {
	return <SomeComponent {...onDragHandle} />
}