Skip to content

Instantly share code, notes, and snippets.

@perry-mitchell
Created September 10, 2017 14:55
Show Gist options
  • Save perry-mitchell/414d6f87d71bfe071fcf8e7a5c94ed0c to your computer and use it in GitHub Desktop.
Save perry-mitchell/414d6f87d71bfe071fcf8e7a5c94ed0c to your computer and use it in GitHub Desktop.
Linda Dynamic Challenge
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
const firstNames = ["Perry", "Linda", "Tom", "Noora", "Daniel"];
const lastNames = ["Mitchell", "Damario", "Jerry", "Suojansalo", "Bailo"];
function getName() {
const numFirstNames = firstNames.length;
const numLastNames = lastNames.length;
const firstNameIndex = Math.floor(Math.random() * numFirstNames);
const lastNameIndex = Math.floor(Math.random() * numLastNames);
const firstName = firstNames[firstNameIndex];
const lastName = lastNames[lastNameIndex];
return `${firstName} ${lastName}`;
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
people: []
};
}
componentWillMount() {
this.load();
}
addPerson() {
const name = getName();
this.setState({ people: [ ...this.state.people, name ] }, () => {
this.save();
});
}
deletePerson(index) {
const newPeople = this.state.people;
newPeople.splice(index, 1);
this.setState({ people: newPeople }, () => {
this.save();
});
}
load() {
const peopleRaw = window.localStorage.getItem("people") || "[]";
const people = JSON.parse(peopleRaw);
this.setState({ people });
}
render() {
return (
<div>
<button onClick={() => this.addPerson()}>Add</button>
<ul>
{this.state.people.map((person, i) =>
<li key={i}>
<span>{person}</span>
<button onClick={() => this.deletePerson(i)}>X</button>
</li>
)}
</ul>
</div>
);
}
save() {
window.localStorage.setItem("people", JSON.stringify(this.state.people));
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment