I need to know how to update the state list using an inline function, and not a stateless component. I’m almost there and Id like someone to show me that’s possible.
It’s the Shopping List code - there is a video in FFC Yt channel about it (link:React Basics - Beau teaches JavaScript - YouTube).
So, here’s my code so far. Below render, I need only to update listItems so that the item clicked on will be deleted from the list. The author used a stateless functional component to do it. Id like to do it inline.
class ShoppingList extends React.Component{
constructor(){
super();
this.state = {list:["potatoes", "eggs", "curly braces", "onions"]};
}
addItem(){
var item = document.getElementById("listItem").value;
document.getElementById("listItem").value = "";
var newList = this.state.list.slice();
newList.push(item);
this.setState({list:newList});
}
onCLicky(index){
var newList = this.state.list.slice();
newList.splice(index,1);
this.setState({list:newList});
}
render(){
var listItems = [];
this.state.list.forEach((item,i)=>{listItems.push(()=>{<li onClick={this.onClicky(i)}>{item}</li>})})
return (
<div>
<h1>Cheap Shopping List for {this.props.user}</h1>
<input type="text" id="listItem" placeholder="Shot Here"/>
<button type="button" onClick={()=> this.addItem()}>1 More</button>
<ul>
{listItems}
</ul>
</div>
);
}
}
ReactDOM.render(
<ShoppingList user="Caio Sa"/>,
document.getElementById('container')
);
And here’s his solution:
function ListItem(props) {
return (
<li onClick={props.onClick}>
{props.item}
</li>
);
}
class ShoppingList extends React.Component {
constructor() {
super();
this.state = {
list: ['unicycle', 'juggling clubs', 'stilts']
};
}
addItem() {
var item = document.getElementById("listItem").value;
document.getElementById("listItem").value = "";
var newList = this.state.list.slice();
newList.push(item);
this.setState({list: newList});
}
onClick(index) {
var newList = this.state.list.slice();
newList.splice(index, 1);
this.setState({list: newList});
}
render() {
var listItems = [];
this.state.list.forEach((item, i) => {
listItems.push(<ListItem item={item} onClick={() => this.onClick(i)} />)
});
return (
<div className="shopping-list">
<h1>Shopping List for {this.props.name}</h1>
<input type="text" id="listItem" placeholder="Add item"/>
<button type="button" onClick={() => this.addItem()}>Add</button>
<ul>
{listItems}
</ul>
</div>
);
}
}
ReactDOM.render(
<ShoppingList name="Beau" />,
document.getElementById('container')
);
Thanks a lot! You all are amazin’!