Event Handlers
Edit this pageEvent handlers are functions that are called in response to a specific event occurring in the browser, such as when a user clicks or taps on an element.
To add an event handler to an element, you can use the on
prefix followed by the event name, and assign it a function.
When using event handlers in Solid, they can be written using camelCase or all lowercase.
This is to avoid the costly process of continuously attaching and detaching listeners. Since event handlers are called like regular functions upon each event trigger, there's no inherent need for them to be reactive.
If necessary, you can write your handlers to call a reactive source:
tsx <div onClick={() => props.handleClick?.()} />
Event delegation
Instead of attaching event listeners to every individual element, Solid uses artificial event delegation. This means that event listeners are attached to the root element and events are captured as they bubble up.
By keeping the number of event listeners to a minimum, events can be captured more effectively. This is especially useful when working with large lists of elements, such as in a table or list.
Supported events such as click
, mouseover
, and keydown
are just a few examples that are optimized in this way.
To view the full list see the references below.
If you need to attach an event listener to an element that is not supported by Solid's event delegation, you can use the on: prefix followed by the event name, and assign it a function.
Binding events
In Solid, event handlers can be bound by passing an array to the event handler. The second item of the array is supplied as the handler's first argument.
In this example, the string 'Hello!'
(the second item in the array) is passed as the data parameter (the first argument of the handler function) when the button is clicked.
By binding events in this way, the overhead of using JavaScript's bind method is avoided.
Delegated Events
You can also view this list in our source code (see DelegatedEvents).