Last active
September 28, 2018 16:42
-
-
Save christopherscott/55b09c61467cb51b06e7415438eb0fa1 to your computer and use it in GitHub Desktop.
adding/removing limited num items, react
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 { | |
state = { | |
contacts: [], | |
} | |
handleAddContact = (evt) => { | |
const { contacts } = this.state; | |
const name = this.input.value; | |
const newContacts = contacts.concat({ name }); | |
this.setState({ contacts: newContacts }) | |
}; | |
handleRemove = (index) => (evt) => { | |
const { contacts } = this.state; | |
const newContacts = contacts.slice() | |
newContacts.splice(index, 1); | |
this.setState({ contacts: newContacts }) | |
}; | |
handleChange = (index) => (evt) => { | |
const { contacts } = this.state; | |
const newContacts = contacts.slice() | |
newContacts[index].name = evt.target.value; | |
this.setState({ contacts: newContacts }); | |
}; | |
render() { | |
const { contacts } = this.state; | |
return ( | |
<div className="App"> | |
<header className="App-header"> | |
<img src={logo} className="App-logo" alt="logo" /> | |
<h1 className="App-title">Welcome to React</h1> | |
</header> | |
<p className="App-intro"> | |
To get started, edit <code>src/App.js</code> and save to reload. | |
</p> | |
<div>contacts:</div> | |
<ul style={{ textAlign: 'left', width: 300, border: '1px solid black', padding: 10 }}> | |
{contacts.map((contact, i) => ( | |
<li key={i} style={{ margin: 10, background: 'gray' }}> | |
key: {i}, name: {contact.name} <button onClick={this.handleRemove(i)}>remove</button> | |
<input type="text" value={contact.name} onChange={this.handleChange(i)} /> | |
</li> | |
))} | |
</ul> | |
<div> | |
{contacts.length < 6 && ( | |
<div> | |
<label htmlFor="contact">Add contact</label> | |
<input type="text" id="contact" ref={node => this.input = node} /> | |
<button onClick={this.handleAddContact}>submit</button> | |
</div> | |
)} | |
</div> | |
</div> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment