Last active
September 5, 2016 00:18
-
-
Save wesbasinger/4ed6aad8f0448f3ede63d33c8d3bc66b to your computer and use it in GitHub Desktop.
Adding React Components with Button Clicks
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
var React = require('react'); | |
var OpenResponse = React.createClass({ | |
render: function() { | |
return ( | |
<div> | |
Open Response | |
</div> | |
) | |
} | |
}); | |
var New = React.createClass({ | |
getInitialState: function() { | |
return { | |
myArr: [{id:1, name: "Some name"}] | |
} | |
}, | |
addChild: function() { | |
this.setState({ | |
myArr: this.state.myArr.concat([{id:2, name:"other name"}]) | |
}) | |
}, | |
render: function() { | |
return( | |
<div> | |
<button onClick={this.addChild}>Add Component</button> | |
{ | |
this.state.myArr.map(function(item) { | |
return <OpenResponse key={item[0].id} /> | |
}) | |
} | |
</div> | |
) | |
} | |
}); |
Using destructuring and arrow functions would make it even better than that, in my opinion.
const { myArr } = this.state;
const items = myArr
.map(i => <OpenResponse key={i.id} />);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now, just my personal preference, but I find it a lot easier and cleaner to keep my code out of my JSX. If I was writing this, I'd have:
I find that writing my views this way makes them much more readable in the future.