Reputation: 392
In my app I have two child components, 'FoodScreen', 'OperationScreen' and a parent Component 'Desk'. Am passing a Json variable array to FoodScreen component to select the item.
When I press the button in Child1 component, it should pass the value for parent, and then the parent should pass the value for child2
Desk Component as :
const nameList = [
{
"id": 111,
"name": "Leanne Graham",
"username": "Bret"
}
},
{
"id": 112,
"name": "Ervin Howell",
"username": "Antonette"
}
}
];
let selectedItem = null;
let item = (selectedItem == null) ? 0 : nameList.find(x => x.id === selectedItem);
class SalesDesk extends Component {
render() {
return <div>
<div className="Background">
<Header/>
<div className="Main">
<FoodScreen itemlist={nameList}/>
<OperationScreen item={item}/>
</div>
<Footer/>
</div>
</div>
}
}
where a 'select ID' state is updated by a click event in the 'FoodScreen Component', like so:
class SdFoodScreen extends Component {
render() {
return <div className="sdFoodScreenMain">
{
this.props.itemlist.map(items =>
<div className="sdFoodBoxes" key={items.id}>
{items.id}
{items.name}
<button onClick={() => this.selectItem(items.id)}> Select ID </button>
</div>
)
}
</div>;
}
constructor(props) {
super(props);
this.state = {
selectedItem : null
}
}
selectItem(itemID) {
this.setState({
selectedItem : itemID
})
}
}
And My 2nd Child component as :
class OperationScreen extends Component {
render() {
let selectedItem = this.props.item;
console.log(selectedItem);
}
}
Whenever I click the button in FoodScreen component, the value should be passed to the Parent 'Salesdesk' component, so I could go pass the value to Child2 component, and print on the console.
I would prefer I there is a way to get rid of the If condition in the Parent class, to have better code structure, as am new to React.
Upvotes: 0
Views: 70
Reputation: 201
You will need to pass a callback function to a child element to update a value in the parent class. You can restructure it in the following way -
In FoodScreen, update the onClick handler to call the callback function and pass the item as an argument -
...
<button onClick={() => this.props.onSelect(item)}> Select ID </button>
...
Then on the SalesDesk class, you can pass the callback handler while using the FoodScreen component
<FoodScreen itemlist={nameList} onSelect={this.updateSelection}/>
and you can update the selected item using this new callback function
updateSelected = (item) => {
this.setState({selectedItem: item});
}
now you can pass selectedItem to OperationScreen
<OperationScreen item={selectedItem}/>
EDIT:
Upvotes: 2