Why does it work when I do "state:" and not "tasks:" in the addItem() function. I thought that the syntax is that you put the state that you want to change, which in this will be tasks:
import React from 'react';
import './App.css';
class App extends React.Component {
constructor(){
super();
this.state = {
value: '',
tasks: []
};
this.handleChange = this.handleChange.bind(this)
this.addItem = this.addItem.bind(this)
}
handleChange(event) {
this.setState({
value: event.target.value
})
}
addItem(){
this.setState({
state: this.state.tasks.push(this.state.value),
value: ''
})
}
render(){
const itemList = this.state.tasks.map((num,index) => <li key={index}>{num}</li>)
return(
<div>
<input type="text" value={this.state.value} onChange={this.handleChange}></input>
<button onClick={this.addItem}>+</button>
<button>-</button>
<ul>{itemList}</ul>
</div>
)
}
}
export default App;
First of all you are mutating your state, this is the first rule when dealing with react state management. Never Mutate state. and you need to wrapper your event handlers in an anonymous function so you can pass you event object. This is your code fixed below---
import React from 'react';
import './App.css';
class App extends React.Component {
constructor(props){
super(props);
this.state = {
value: '',
tasks: []
};
this.handleChange = this.handleChange.bind(this)
this.addItem = this.addItem.bind(this)
}
handleChange(event) {
this.setState({
value: event.target.value
})
}
addItem(){
const tempTasksArray = this.state.tasks.concat(this.state.value)
this.setState({
tasks: tempTasksArray,
})
}
render(){
const itemList = this.state.tasks.map((num,index) => <li key={index}>{num}</li>)
return(
<div>
<input
type="text"
value={ this.state.value }
onChange={(event) => this.handleChange(event) } />
<button onClick={() => this.addItem }>
+
</button>
<button>
-
</button>
<ul>{ itemList }</ul>
</div>
)}
}
export default App;