Forked from makarovas/react-js-how-to-append-a-component-on-click
Created
June 9, 2023 08:49
-
-
Save ichengzi/75b4e05a264fc2e6fa6aaef45332f101 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
class AppComponent extends React.Component { | |
state = { | |
numChildren: 0 | |
} | |
render () { | |
const children = []; | |
for (var i = 0; i < this.state.numChildren; i += 1) { | |
children.push(<ChildComponent key={i} number={i} />); | |
}; | |
return ( | |
<ParentComponent addChild={this.onAddChild}> | |
{children} | |
</ParentComponent> | |
); | |
} | |
onAddChild = () => { | |
this.setState({ | |
numChildren: this.state.numChildren + 1 | |
}); | |
} | |
} | |
const ParentComponent = props => ( | |
<div className="card calculator"> | |
<p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p> | |
<div id="children-pane"> | |
{props.children} | |
</div> | |
</div> | |
); | |
const ChildComponent = props => <div>{"I am child " + props.number}</div>; | |
ReactDOM.render(<AppComponent/>, document.getElementById('root')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment