Tarrence
Tarrence

Reputation: 794

Pushing event handlers to parent components

If, for example, I have a spreadsheet and want to attach handlers to cells to handle a users interaction. Typically, you would attach the handlers to the cell component itself. But if you are creating thousands of cells, this seems rather inefficient.

If I had a component hierarchy where SheetComponent -> CellComponents how can I attach a single handler to SheetComponent to handle each cell interaction? When the user interacts, I would like to have access to CellComponents props in order to identify which was clicked.

Upvotes: 0

Views: 66

Answers (1)

WiredPrairie
WiredPrairie

Reputation: 59793

DOM events, when using React are synthetic ... they are all handled at the document level and then synthesized across all handlers. So, for DOM events, a handler hasn't been attached to each element for each event. However, that still means there is overhead that can't be avoided as your components would need to be notified that an event has occurred.

For communicating to the SheetComponent from a CellComponent, you could simply add your own event as a property: onCellActivated for example. If you have more than a couple, you could, instead of having lots of events needing to be wired up, you could have a generic event with an argument set to the type of event:

 onCellEvent({ eventType: 'activation', cell: this })

That pattern starts to look more like an Action Creator/Action following the Flux pattern (without the Dispatcher and Store of course).

Instead of relying on your own events, you could use a Flux/Action/Dispatcher pattern potentially to relay key events to a centralized location (like the SheetComponent) and from there handle the interaction. With the action dispatched, you would include the key information about the cell where the interaction took place.

But, you might want to test the performance of a more traditional event model first as this might add extra complexity with little actual benefit.

You might also want to take some inspiration from Facebook's Fixed Data Table component, written for React. It's designed to handle thousands of rows of data efficiently.

Upvotes: 1

Related Questions