Introduction
I am currently exploring Solid.js and facing a challenge in adding multiple event handlers to the same HTML element from different components using JSX. While it's straightforward in Vue, I have noticed that Solid.js overrides events based on how they are added. I have demonstrated this behavior in both frameworks in an example which you can access here. In Vue, adding multiple event handlers works as expected, but in Solid, any additional event handler seems to override the previous one for a single event.
If you want to compare behaviors, you can toggle between useDivAsComponent
in Solid and useDivAsComponent
in Vue. Vue consistently handles multiple event handlers attached to a component or HTML element, while Solid's behavior varies depending on where events are added - either to an HTML element or another component.
My question is whether there is a simple way to attach multiple event handlers to the same HTML element using different components defined with JSX in Solid?
Details
In a scenario where I need to add DOM event handlers to the root element of a component, I also want users of the component to be able to append their own DOM event handlers to it. If the root element is like
(props) => <div {...props} />
, only the internal event handlers within the component are effective (external ones will be overruled). This happens because Solid merges props, resulting in only the last event handler being retained instead of utilizing addEventListener
.
However, if the component's root element is a standard <div />
, Solid generates code in a way that preserves both sets of event handlers. The built code shows Solid using addEventListener()
, which aligns with expectations.
Potential Solutions
To work around this issue, one approach could involve passing a reference to the inner component (
<InnerComponent ref={ref} />
) to the parent and manually adding event listeners to prevent additional events from getting overridden (ref.addEventListener(...)
). Although effective, this method may not be as user-friendly compared to other frameworks.
Alternatively, ensuring that the inner component where event handlers are applied is a regular <div />
may prompt Solid's compiler to generate code that incorporates event listeners instead of merging (and replacing) event handler props.
I am eager to discover a more seamless way to include multiple events in JSX, if feasible.