# Handling Multiple Inputs
To handle multiple controlled inputs, add the HTML name attribute to each JSX input element and let handler function decide the appropriate key in state to update based on event.target.name.
## Passing Data Up to a Parent Component
- downward data flow. “Smart” parent components with simpler child components.
- But it is common for form components to manage their own state
- the smarter parent component usually has a doSomethingOnSubmit method to update its state after the form submission.
1) The child component will call this method which will then update the parent’s state.
2) The child is still appropriately “dumber”, all it knows is to pass its data into a function it was given.
## Shopping List Example
- Parent Component: ShoppingList (manages a list of shopping items)
- Child Component: NewListItemForm (a form to add a new shopping item to the list)
import React, { Component } from 'react';
import ShoppingListForm from './ShoppingListForm';
import { v4 as uuidv4 } from 'uuid';
class ShoppingList extends Component {
constructor(props) {
super(props);
this.state = {
items: [
{ name: "Milk", qty: "1", price: "12", id: uuidv4() }
]
};
this.renderItems = this.renderItems.bind(this);
this.addItems = this.addItems.bind(this);
}
addItems(item) {
let newItem = { ...item, id: uuidv4() };
this.setState(state => ({
items: [...state.items, newItem]
}))
}
renderItems() {
return (
<ul>
{this.state.items.map(item => (
<li key={item.id}>
{item.name}: {item.qty} / $ {item.price}
</li>
))}
</ul>
);
}
render() {
return (
<div>
<h1>Shopping List</h1>
{this.renderItems()}
<ShoppingListForm addItems={this.addItems} />
</div>
)
}
}
export default ShoppingList;
import React, { Component } from 'react';
class ShoppingListForm extends Component {
constructor(props) {
super(props);
this.state = { name: "", qty: "", price: "" };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(evt) {
evt.preventDefault();
this.props.addItems(this.state);
this.setState({ name: "", qty: "", price: "" })
}
handleChange(evt) {
this.setState({
[evt.target.name]: evt.target.value
});
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label htmlFor="name">Name:</label>
<input
id="name"
name="name"
value={this.state.name}
onChange={this.handleChange}
/>
<label htmlFor="qty">QTY: </label>
<input
id="qty"
name="qty"
value={this.state.qty}
onChange={this.handleChange}
/>
<label htmlFor="price">Price: </label>
<input
id="price"
name="price"
value={this.state.price}
onChange={this.handleChange}
/>
<button>Submit</button>
</form>
</div >
)
}
}
export default ShoppingListForm;
'react' 카테고리의 다른 글
React form control (0) | 2020.06.14 |
---|---|
React events : event method binding and passing method to child (0) | 2020.06.14 |
State exercise : coin flipper (0) | 2020.06.14 |
State exercise : lottery balls (0) | 2020.06.14 |
More State : data structure and designing state (0) | 2020.06.14 |