I'm trying to figure out how to clone an existing element with additional props.
For reference:
this.mainContent = <Hello message="Hello world!" />
I attempted to do something like
React.createElement(this.mainContent, Object.assign({}, this.mainContent.props, { anotherMessage: "nice to meet ya!" }));
but it's not working.
How would I accomplish this?
There is no way to pass props up to a parent component from a child component. We will revisit this caveat later in this tutorial. It's also important to note that React's props are read only (immutable). As a developer, you should never mutate props but only read them in your components.
You can pass a component as props in React by using the built-in children prop. All elements you pass between the opening and closing tags of a component get assigned to the children prop.
A component cannot update its own props unless they are arrays or objects (having a component update its own props even if possible is an anti-pattern), but can update its state and the props of its children.
You need to clone the element and add the additional props using React.cloneElement
e.g:
const ClonedElementWithMoreProps = React.cloneElement( this.mainContent, { anotherMessage: "nice to meet ya!" } ); // now render the new cloned element?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With