I am new to React and trying to learn the framework from the ground up. I have built a few simple components(for a typical restaurant website), but I am facing problems understanding event handling. Basically, I have an app component which just calls the Main component, which in turn calls a Menu and Dishdetail component. So the hierarchy is App --> Main --> (Menu and Dishdetail).
App (Just call Main)
return (
<div>
**<Main/>**
</div>
);
Main (Calling Menu component with props) Here I use the onClick event.
**<Menu dishes={this.state.dishes}
onClick={(dishId) => this.onDishSelect(dishId)} />**
Menu (Using the onClick event to render something using the RenderMenuItem functional component)
const menu = props.dishes.map((dish) => {
return (
<div key={dish.id} className="col-12 col-md-5 mt-5 m-1">
**<RenderMenuItem dish={dish} onClick={props.onClick} />**
</div>
)
});
The RenderMenuItem functional component:
function RenderMenuItem({ dish, **onClick** }) {
return (
**<Card onClick={() => onClick(dish.id)}>**
<CardImg width='100%' src={dish.image} alt={dish.name} />
<CardImgOverlay>
<CardTitle>{dish.name}</CardTitle>
</CardImgOverlay>
</Card>
)}
Everything is working fine but I am having problems understanding the event handler and I'm also new to arrow functions. According to my understanding:
App calls the Main component which in turn calls the menu component with the 2 props. Here I use the arrow function as a response to onClick event to set the state of the component. ( So I know which dish is selected). But I am also passing it as a prop? Or am I not?
Once the execution flows into the Menu component it calls the RenderMenuItem with the dish selected in the map 'loop' and the same prop onClick it received. What is going on here? Is it just instructing the program to call the function in the Main component (just change state again as in point 1)?
In the RenderMenuItem component I have no idea what is going on with the onClick attribute aside from the fact that it is calling a function called onClick with parameter dish.id. Can someone explain in detail what exactly happens when you pass an event attribute like onClick to child components?