Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: adding props to an existing component

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?

like image 528
zoopz Avatar asked Apr 20 '16 16:04

zoopz


People also ask

How do you pass a prop to a component in React?

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.

How do you pass components with props as props?

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.

Can a component update its own props?

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.


1 Answers

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? 
like image 113
Salakar Avatar answered Sep 21 '22 13:09

Salakar