-
-
Save SabrinaMarkon/4e0f3007b042600a54e90f198de69e68 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