I am still a noob at React and in many examples on the internet, I see this variation in rendering child elements which I find confusing. Normally I see this:
In fact, React.cloneElement
is not strictly associated with this.props.children
.
It's useful whenever you need to clone react elements(PropTypes.element
) to add/override props, without wanting the parent to have knowledge about those component internals(e.g, attaching event handlers or assigning key
/ref
attributes).
Also react elements are immutable.
React.cloneElement( element, [props], [...children] ) is almost equivalent to:
{children}
However, the children
prop in React is especially used for containment (aka composition), pairing with React.Children
API and React.cloneElement
, component that uses props.children can handle more logic(e.g., state transitions, events, DOM measurements etc) internally while yielding the rendering part to wherever it's used, React Router
One last thing that worth mentioning is that react elements are not restricted to props.children.
function SplitPane(props) {
return (
{props.left}
{props.right}
);
}
function App() {
return (
}
right={
} />
);
}
They can be whatever props that makes sense, the key was to define a good contract for the component, so that the consumers of it can be decoupled from the underlying implementation details, regardless whether it's using React.Children
, React.cloneElement
, or even React.createContext
.