createElement vs cloneElement: What's the Difference?
In React, both createElement
and cloneElement
are used to create React elements, but they serve different purposes.
1. React.createElement
-
Purpose: Used to create a brand new React element from scratch.
-
Syntax:
React.createElement(type, props, ...children)
-
Parameters:
type
: The type of the element (like'div'
,'h1'
, or a React component).props
: An object containing the properties (attributes) you want to assign.children
: The child elements or text inside the element.
-
Example:
const element = React.createElement('button', { className: 'btn' }, 'Click Me');
This creates a
<button class="btn">Click Me</button>
. -
When to use: Mostly used internally by JSX (
<div>
) transpilation. Developers rarely call it directly.
2. React.cloneElement
-
Purpose: Used to clone an existing React element and optionally modify its props or children.
-
Syntax:
React.cloneElement(element, [props], [...children])
-
Parameters:
element
: The existing React element you want to clone.props
: (Optional) New props to merge with or override the original element's props.children
: (Optional) New children to replace the original element's children.
-
Example:
const originalElement = <button className="btn">Click Me</button>; const clonedElement = React.cloneElement(originalElement, { disabled: true });
This produces a
<button class="btn" disabled>Click Me</button>
. -
When to use: Useful when you want to take a child component and inject additional props or modify it before rendering — often seen in component libraries.
Quick Summary
Feature | createElement | cloneElement |
---|---|---|
Purpose | Create a new element | Clone and modify an existing element |
Typical Use Case | JSX under the hood | Enhance or override props of children |
Parameters | type, props, children | element, newProps, newChildren |
Example Use | React.createElement('div', {...}) | React.cloneElement(existingElement, {...}) |
Tip:
createElement
= start from zerocloneElement
= copy and customize