Reputation: 9365
I have an app that looks roughly like this:
class App extends React.Component {
render(){
var ComponentTwo = this.props.getComponentTwo();
return (
<div>
<ComponentOne />
{ComponentTwo ? <ComponentTwo /> : []}
</div>
);
}
}
The ComponentTwo is not always the same component class and sometimes it needs to interact with ComponentOne - namely - select certain elements from it and attach some listeners to them.
I want this functionality to come with ComponentTwo because it's only needed when ComponentTwo is loaded and it comes with a lot of code.
What are the best practice to allow one component to dynamically extend another sibling component?
Upvotes: 1
Views: 448
Reputation: 1630
I believe that the correct way to implement such a scenario in React is to change state of the App component after some action in ComponentTwo and then pass state changes to ComponentOne:
onComponentTwoAction: function(someValueFromAction) {
this.setState({
componentOneProp: someValueFromAction
});
},
render: function(){
var ComponentTwo = this.props.getComponentTwo();
return (
<div>
<ComponentOne componentOneProp={this.state.componentOneProp}/>
{ComponentTwo ? <ComponentTwo onAction={this.onComponentTwoAction}/> : []}
</div>
);
}
Upvotes: 1