Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save xyzdata/5acc4a357722e9e2636009fbd6846338 to your computer and use it in GitHub Desktop.
Save xyzdata/5acc4a357722e9e2636009fbd6846338 to your computer and use it in GitHub Desktop.
dynamically-add-child-components-in-react

dynamically-add-child-components-in-react

https://stackoverflow.com/questions/36651583/dynamically-add-child-components-in-react

    
var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(
    <App>
        <SampleComponent name="SomeName"/> 
    <App>, 
    document.body
);
    
var App = React.createClass({
    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                {
                    this.props.children
                }
            </div>
        );
    }
});
    
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>
        );
    }

});
@xgqfrms-GitHub
Copy link

xgqfrms-GitHub commented Jun 27, 2017

@xgqfrms-GitHub
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment