R
R
real22102020-04-13 18:01:37
React
real2210, 2020-04-13 18:01:37

Is it possible to add a react element to children?

I get the children in the component, then I create a copy and add a new element to props.children, when rendering this pie, I get an error that key is not specified. But my new element was successfully added to the children.
Maybe it's because you can't and shouldn't.

const element = <div>element</div>;
    console.log(children);
    const newChildren = { ...children };
    const childrenWithElement ={
            ...newChildren,
            props: {
                ...newChildren.props,
                children: [...newChildren.props.children, element]
            }
        };
    console.log(childrenWithElement);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Osher, 2020-04-13
@miraage

Use the React.Children API to manipulate children.
And even better, don’t use it at all, but try to compose a composition somehow. Here it depends on the specific case.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question