I know this is a simple problem but I am new with React.
What am I missing to get the index of a value that I click on? I am simply trying to say, when a user clicks delete, delete that value from the array.
<!DOCTYPE html>
<html>
<head>
<title>
React Practice
</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.js"></script>
</head>
<body>
<div id="app">
<!-- This element's contents will be replaced with your component. -->
</div>
<script type="text/babel">
var MainContainer = React.createClass({
getInitialState: function(){
return {
name: 'JK_MNO',
friends: [],
text: ''
}
},
handleChange: function(e){
this.setState({
text: e.target.value
});
},
handleSubmit: function(e){
e.preventDefault();
if(this.state.text !== '') {
var nextfriend = this.state.friends.concat([{
text: this.state.text, id: Date.now()
}]);
var nextText = '';
this.setState({
friends: nextfriend, text: nextText
});
}
},
handleDelete: function(e){
for (var i = this.state.friends.length - 1; i >= 0; i--) {
this.state.friends[i]
};
this.state.friends.splice(i, 1);
this.setState({
friends: this.state.friends
});
},
render: function(){
return (
<div>
<h3> Name: {this.state.name} </h3>
<ShowList friends={this.state.friends} handleDelete={this.handleDelete} />
<form onSubmit={this.handleSubmit} >
Enter Friends: <input className="friendInput" onChange={this.handleChange} value={this.state.text} />
</form>
</div>
);
}
});
var ShowList = React.createClass({
render: function() {
var createFriend = function(friend) {
return (
<li key={friend.id}>{friend.text} <button onClick={this.props.handleDelete}>Delete</button> </li>
);
};
return <ul>{this.props.friends.map(createFriend.bind(this))}</ul>;
}
});
ReactDOM.render(<MainContainer />, document.getElementById('app'));
</script>