I'm trying to create a todo app in React. I'm currently trying to print the input when i press the button, but it is not working. Can anyone help to check my syntax!
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.state.tasks.push(this.state.value)
}
render(){
return(
<div>
<input type="text" value={this.state.value} onChange={this.handleChange}></input>
<button onClick={this.addItem}> </button>
<button>-</button>
<h1>{this.state.tasks}</h1>
</div>
)
}
}
export default App;
CodePudding user response:
To change the state you should use this.setState
. Refer to https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly. Reading React documentation might save you a lot of time overall.
CodePudding user response:
Modifying state directly is not the correct way!
instead use setState:
this.setState({
tasks: this.state.tasks.concat(this.state.value)
})
CodePudding user response:
You need to setState task
addItem() {
const newTask = [this.state.value, ...this.state.tasks];
this.setState({ tasks: newTask });
this.setState({ value: "" });
}