I'm quite newly to React Js and I'm really confusing about below scenario. I have an array called availableShops in my parent component I just update it in child component using setState. I want to keep setState method in my child component also.
Parent:
import React, { Component } from 'react';
import Child from './shop-with-price';
export default class Parent extends Component {
constructor(props) {
super(props);
this.state = {
availableShops:[]
}
}
render{
return (
<div>
<Child
shops = {this.state.shops}
onChange = {this.handleInputChange}
avalilableShops = {this.state.avalilableShops}
/>
</div>
);
}
}
Child Component
import React, { Component } from 'react';
export default class Child extends Component {
constructor(props) {
super(props);
this.state = {
avalilableShops: this.props.avalilableShops,
}
}
handleInputChange(e) {
const target = e.target;
const name = target.name;
const value = target.value;
this.setState({
[name]: value
});
}
createShops(e){
e.preventDefault();
let shopName = this.state.shop_name;
let phonePrice = this.state.phone_price;
const phoneInfo = {'shop_name':shopName, 'phone_price':phonePrice};
this.setState((preState) => ({
avalilableShops: [...preState.avalilableShops, phoneInfo]
}), ()=>{ console.log(this.state.avalilableShops)});
}
render() {
const rows = this.state.avalilableShops.map((record,index) => {
return (
<tr key={index}>
<td>{record.shop_name}</td>
<td>{record.phone_price}</td>
<td>
<button
type="button"
className="btn btn-primary"
// onChange={this.createShops}
>
Delete
</button>
</td>
</tr>
);
});
return (
<div>
<label>Add shops that phone already available...</label>
<div className="row">
<div className="col-md-6">
<div className="form-group">
<select
name="shop_name"
className="form-control select2"
onChange={this.handleInputChange}
>
{this.state.shops.map((shops, index) => (
<option key={index} value={shops.name}>
{shops.name}
</option>
))}
;
</select>
</div>
</div>
<div className="col-md-4">
<div className="form-group">
<input
type="number"
name="phone_price"
placeholder="Price"
className="form-control"
value={this.state.phone_price}
onChange={this.handleInputChange}
/>
</div>
</div>
<div className="col-md-2">
<button
type="button"
className="btn btn-primary"
onClick={this.createShops.bind(this)}
>
Add
</button>
</div>
</div>
<br />
<table className="table table-striped">
<thead>
<tr>
<th scope="col">Shop name</th>
<th scope="col">Price</th>
<th scope="col">Remove</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
</div>
);
}
}
I want to all these changes happen in child component because & within createShop method I update my availableShops using spread operator. Rendering components fine. How ever availableShops array doesn't update now but I want to use it in parent component also. Please help me to figure out this problem.

availableShopsfrom the parent component to the child component if it's empty?avalilableShopsin my parent component?