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> | |
) | |
} | |
}); |
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.
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
You don't need the
[0]
in your open responsekey
property.item
is not an array which you would call an index of.item
is the object within the array. So, you would saykey={item.id}
.