React Reference ยท Top-Level React APIs
React cloneElement() function
Reference for React.cloneElement: copy an element with merged props and new children, how key and ref behave, why it is legacy, and better alternatives.
cloneElement takes an existing React element and returns a new element of the same type, with the props you pass merged over the original ones. The original is not changed. The key is kept, and you can pass a new one.
It is used when a component needs to adjust the elements it receives as children, for example to inject an onClick or a className. The React team considers this pattern fragile and legacy: the child must cooperate, and it breaks as soon as the element is wrapped in another component. Prefer passing data through props, render props or context.
import { cloneElement } from 'react'; const bigger = cloneElement(<button>OK</button>, { className: 'big' });
Try it
Syntax
function cloneElement( element: ReactElement, props?: object | null, ...children: ReactNode[] ): ReactElement;
| Name | Description |
|---|---|
element |
The element to copy. Must be a valid element (not a string or number). |
props |
Props to add or override. Merged shallowly: your values replace existing ones with the same name; others are kept. May include key, and ref to override those. |
...children |
If given, they replace the original children. If omitted, the original children are kept. |
Returns: a new element with the same type.
Usage notes
- Only the element is copied, not what it renders. The clone has the same type and merged props; the component itself runs later, as usual.
undefinedoverrides. Passing{ title: undefined }replaces the originaltitlewithundefined, so a default value declared in the component applies. Only props you leave out are kept.- Wrappers break it. If a child is wrapped in another component (
<Wrapper><Button /></Wrapper>), you clone the wrapper's element, and the extra props never reach the button. Context or an explicit prop avoids this. - Event handlers are replaced, not combined. Passing
onClickoverrides the child's ownonClick. Call the original inside yours:onClick: (e) => { child.props.onClick?.(e); mine(e); }. - Non-elements:
cloneElement(null)throws, and text or numbers give a meaningless empty element instead of an error. Combine it withChildren.mapand check withisValidElementfirst. - Alternatives: context (createContext) for implicit sharing, a render prop for explicit data, or a custom hook.
- React 19: to override the ref, pass
refin the props argument; the original element's ref is read fromelement.props.ref.