Skip to content

Event Handlers on Fragments #12051

Description

@sebmarkbage

The use case is when an abstraction wants to listen to some event bubbling up and intercept the event somehow.

function Abstraction(props) {
  return <div onClick={() => props.onAction()}>{props.children}</div>;
}

Perhaps there is some state and context involved too.

This works fine today as long as you can wrap it in a <div />. However, you can't necessarily always do that. I hear that some of this will be relaxed but conceptually I think the constraints will remain in many environment that you don't want a wrapper element around these.

<ul>
  <Abstraction onAction={...}>
    <li>A</li>
    <li>B</li>
  </Abstraction>
</ul>
<table>
  <tbody>
    <Abstraction onAction={...}>
      <tr><td>A</td></tr>
      <tr><td>B</td></tr>
    </Abstraction>
    <Abstraction onAction={...}>
      <tr><td>A</td></tr>
      <tr><td>B</td></tr>
    </Abstraction>
  </tbody>
</table>

It would be nice to be able to use fragments for this.

function Abstraction(props) {
  return <Fragment onClick={() => props.onAction()}>{props.children}</Fragment>;
}

It is easy to implement with the synthetic event system but I suspect it is doable with other approaches too (including just inserting an element called <fragment /> in the DOM).

To implement this we'd need somewhere to store the "current" props. We can use the stateNode on fragment fibers to hold that. We also need to schedule commit phase effects whenever the set of event handlers on a fragment changes. In the commit phase we update the stateNode on both Fibers to hold the "current props".

That way when we bubble up the fiber return pointers, we know that stateNode holds the current set of props and those will be the ones we extract event handlers from.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions