Skip to content

Instantly share code, notes, and snippets.

@ygamretuta
Created January 7, 2018 22:33
Show Gist options
  • Save ygamretuta/2e85aa023005672f86e1326ffc8d7032 to your computer and use it in GitHub Desktop.
Save ygamretuta/2e85aa023005672f86e1326ffc8d7032 to your computer and use it in GitHub Desktop.
class CustomerList extends React.Component {
constructor(props){
super(props)
this.state = {
customers: []
}
}
// callback for adding new customer to the list
cbAddCustomer(newCustomer) {
this.setState({
customers: [...this.state.customers, newCustomer]
})
}
render(){
const customers = this.state.customers
return(
<React.Fragment>
{customers.length > 0 &&
{customers.map(customer => (
<Customer name={customer.name} />
))}
}
</React.Fragment>
)
}
}
class AddCustomer extends React.Component {
constructor(props){
name: ''
}
// reflect changes on form immediately
handleChange = (e, {name, value}) => {
this.setState({[name]: value})
}
handleAdd = () => {
this.setState({name: this.state.name})
// pass name to parent callback
this.props.cbAddCustomer({name: name})
}
render(){
const name = this.state.name
<Form.onSubmit={this.handleAdd}>
<Form.Input placeholder='Name' name='name' value={name} onChange={this.handleChange} />
<Button type='submit'>Add</Button>
</Form>
}
}
// customer component, function shorthand
function Customer(props){
return(
<React.Fragment>
<h1>{props.name}</h1>
</React.Fragment>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment