I'm trying to modify and clone the child elements of a component I'm creating and recently noticed that mychildren
type changes depending on how I passchildren
>.
For example, if I pass JSX as a child:
Hello
When I inspect thechildren
structure inMyComponent
, I can see the object as follows:
{ '$$typeof': Symbol(react.element), type: 'div', key: null, ref: null, props: { children: 'hello' }, _owner: null, _store: {} }
Sinceprops.children
exists,React.cloneElement
can use it directly.
If I create a functional component like this:
const Hello: React.FC = () =>hello;
and try to use it like this:
Then the structure of thechildren
object becomes like this:
{ '$$typeof': Symbol(react.element), type: [Function: Hello], key: null, ref: null, props: {}, _owner: null, _store: {} }
I can no longer useReact.cloneElement
unless I callchildren.type()
, but I can't find much documentation on that.
Why does this happen? Is this expected? Is callingchildren.type()
the only way to clone the entire tree of children?
Hello
props
because it has no child objects and we are not passing it a property with a value, soprops
is{}
.What you really want to access and clone are
the child elements of the parent JSX element returned, regardless of their props.
The parent JSX element returned is actually
children.type()
(what the function returns) which has the children wrapped in it (Hello), sochildren.type().props.children is also present here so you can clone it.