React: adding props to an existing component

JavascriptReactjs

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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?

Solution 2 - Javascript

If you don't want to use React.cloneElement(), you can use the following snippet:

function AddExtraProps(Component, extraProps) {
    return <Component.type {...Component.props} {...extraProps} />;
}

Solution 3 - Javascript

React.createElement() takes either a string or a React class type as its first parameter, so that won't work if you're trying to clone an element.

Of course, there's React.cloneElement() instead, which does a deep copy of another React element and can optionally provide new props.

var foo = React.cloneElement(this.mainContent, {anotherMessage: "nice to meet ya!"});

Should work.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzoopzView Question on Stackoverflow
Solution 1 - JavascriptSalakarView Answer on Stackoverflow
Solution 2 - JavascriptEugene IhnatsyeuView Answer on Stackoverflow
Solution 3 - JavascriptjeredView Answer on Stackoverflow