Dynamically add child components in React. You need to pass your components as children, like this:
1 2 3 4 5 6 7 8 |
var App = require('./App.js'); var SampleComponent = require('./SampleComponent.js'); ReactDOM.render( <App> <SampleComponent name="SomeName"/> <App>, document.body ); |
And then append them in the component’s body:
1 2 3 4 5 6 7 8 9 10 11 12 |
var App = React.createClass({ render: function() { return ( <div> <h1>App main component! </h1> { this.props.children } </div> ); } }); |
You don’t need to manually manipulate HTML code, React will do that for you. If you want to add some child components, you just need to change props or state it depends. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
var App = React.createClass({ getInitialState: function(){ return [ {id:1,name:"Some Name"} ] }, addChild: function() { // State change will cause component re-render this.setState(this.state.concat([ {id:2,name:"Another Name"} ])) } render: function() { return ( <div> <h1>App main component! </h1> <button onClick={this.addChild}>Add component</button> { this.state.map((item) => ( <SampleComponent key={item.id} name={item.name}/> )) } </div> ); } }); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.