Skip to content

Instantly share code, notes, and snippets.

@SabrinaMarkon
Forked from ryanjyost/App.js
Created March 31, 2019 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SabrinaMarkon/4e0f3007b042600a54e90f198de69e68 to your computer and use it in GitHub Desktop.
Save SabrinaMarkon/4e0f3007b042600a54e90f198de69e68 to your computer and use it in GitHub Desktop.
App.js for localStorage tutorial - Initial Setup
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}
>
&#43; 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