Last active
March 31, 2019 10:08
-
-
Save ryanjyost/51e2ef817f75242817073528f645f74f to your computer and use it in GitHub Desktop.
App.js for localStorage tutorial - Initial Setup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from "react"; | |
import logo from "./logo.svg"; | |
import "./App.css"; | |
class App extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
newItem: "", | |
list: [] | |
}; | |
} | |
updateInput(key, value) { | |
// update react state | |
this.setState({ [key]: value }); | |
} | |
addItem() { | |
// create a new item | |
const newItem = { | |
id: 1 + Math.random(), | |
value: this.state.newItem.slice() | |
}; | |
// copy current list of items | |
const list = [...this.state.list]; | |
// add the new item to the list | |
list.push(newItem); | |
// update state with new list, reset the new item input | |
this.setState({ | |
list, | |
newItem: "" | |
}); | |
} | |
deleteItem(id) { | |
// copy current list of items | |
const list = [...this.state.list]; | |
// filter out the item being deleted | |
const updatedList = list.filter(item => item.id !== id); | |
this.setState({ list: updatedList }); | |
} | |
render() { | |
return ( | |
<div className="App"> | |
<header className="App-header"> | |
<img src={logo} className="App-logo" alt="logo" /> | |
<h1 className="App-title">Welcome to React LocalStorage Tutorial</h1> | |
</header> | |
<div | |
style={{ | |
padding: 50, | |
textAlign: "left", | |
maxWidth: 500, | |
margin: "auto" | |
}} | |
> | |
Add an item to the list | |
<br /> | |
<input | |
type="text" | |
placeholder="Type item here" | |
value={this.state.newItem} | |
onChange={e => this.updateInput("newItem", e.target.value)} | |
/> | |
<button | |
onClick={() => this.addItem()} | |
disabled={!this.state.newItem.length} | |
> | |
+ Add | |
</button> | |
<br /> <br /> | |
<ul> | |
{this.state.list.map(item => { | |
return ( | |
<li key={item.id}> | |
{item.value} | |
<button onClick={() => this.deleteItem(item.id)}> | |
Remove | |
</button> | |
</li> | |
); | |
})} | |
</ul> | |
</div> | |
</div> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment