I feel like I've tried everything under the sun here but must be missing something very obvious. In the addItem() function
below, I am trying to push a new item into an array and update state, but no matter what I do state just won't change from the initial array.
When I console.log newListItems the new item is included, so everything up to that point is working, it's the actual state that won't update. What am I missing?
addItem Method:
addItem(text){
var newListItems = this.state.listItems;
newListItems.push(text);
console.log(newListItems);
this.setState = ({
listItems : newListItems
});
}
Also i am not getting any error message in console.
Full Code:
import React, { Component } from 'react';
import './App.css';
class ListItem extends Component{
render(){
return (<li>{this.props.title}</li>);
}
}
class AddItem extends Component{
handleClick(){
this.props.addItem('blah');
}
render(){
return (
<div className="additem">
<input type="text" className="newitemname"/>
<span className="btn" onClick={this.handleClick.bind(this)}>Add item</span>
</div>
);
}
}
class App extends Component {
constructor(props){
super(props);
this.state = {
listItems : ['Wash the dishes','Do the laundry','Something else']
};
}
addItem(text){
var newListItems = this.state.listItems;
newListItems.push(text);
console.log(newListItems);
this.setState = ({
listItems : newListItems
});
}
render() {
return (
<div className="App">
<ul>
{this.state.listItems.map(function(item,index){
return (
<ListItem key={index} title={item} />
);
})}
</ul>
<AddItem addItem={this.addItem.bind(this)} />
</div>
);
}
}
export default App;