나만보는개발공부블로그

[React] React.cloneElement 본문

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} />
}

'Web Development > Front' 카테고리의 다른 글

Storybook 적용  (0) 2022.04.27
[React]ref 와 forwardRef  (0) 2021.12.15
[State]상태관리  (0) 2021.03.30
[Angular] Data Binding & Change Detection  (0) 2021.03.12
[Angular] Angular Template Syntax  (0) 2021.03.12