import React, { Component } from "react";
class App extends Component {
state = { items: ["Apple","Banana"], newItem: "" };
add = () => this.state.newItem && this.setState({ items:[...this.state.items,this.state.newItem], newItem:"" });
remove = i => this.setState({ items: this.state.items.filter((_,idx)=>idx!==i) });
render() {
return (
<div>
<h2>List Example</h2>
<input value={this.state.newItem} onChange={e=>this.setState({newItem:e.target.value})} placeholder="Add item"/>
<button onClick={this.add}>Add</button>
<ul>
{this.state.items.map((item,i)=><li key={i}>{item} <button onClick={()=>this.remove(i)}>X</button></li>)}
</ul>
</div>
);
}
}
export default App;
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter