Skip to content

Instantly share code, notes, and snippets.

@wesbasinger
Last active September 5, 2016 00:18
Show Gist options
  • Save wesbasinger/4ed6aad8f0448f3ede63d33c8d3bc66b to your computer and use it in GitHub Desktop.
Save wesbasinger/4ed6aad8f0448f3ede63d33c8d3bc66b to your computer and use it in GitHub Desktop.
Adding React Components with Button Clicks
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>
)
}
});
@rBurgett
Copy link

rBurgett commented Sep 5, 2016

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:

const state = this.state;
const items = state.myArr.map(function(item) {
  return (
    <OpenResponse key={item.id} />
  );
});

return (
  <div>
    <button>...</button>
    {items}
  </div>
);

I find that writing my views this way makes them much more readable in the future.

@rBurgett
Copy link

rBurgett commented Sep 5, 2016

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