Skip to content

Commit 6ac4492

Browse files
authored
Add information on instantiating EventChain directly (#1614)
1 parent 636525e commit 6ac4492

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

docs/wrapping-react/props.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,4 +154,49 @@ class EventHandlerComponent(MyBaseComponent):
154154

155155
```md alert info
156156
# Custom event specs have a few use case where they are particularly useful. If the event returns non-serializable data, you can filter them out so the event can be sent to the backend. You can also use them to transform the data before sending it to the backend.
157+
```
158+
159+
### Emulating Event Handler Behavior Outside a Component
160+
161+
In some instances, you may need to replicate the special behavior applied to
162+
event handlers from outside of a component context. For example if the component
163+
to be wrapped requires event callbacks passed in a dictionary, this can be
164+
achieved by directly instantiating an `EventChain`.
165+
166+
A real-world example of this is the `onEvents` prop of
167+
[`echarts-for-react`](https://www.npmjs.com/package/echarts-for-react) library,
168+
which, unlike a normal event handler, expects a mapping of event handlers like:
169+
170+
```javascript
171+
<ReactECharts
172+
option={this.getOption()}
173+
style={{ height: '300px', width: '100%' }}
174+
onEvents={{
175+
'click': this.onChartClick,
176+
'legendselectchanged': this.onChartLegendselectchanged
177+
}}
178+
/>
179+
```
180+
181+
To achieve this in Reflex, you can create an explicit `EventChain` for each
182+
event handler:
183+
184+
```python
185+
@classmethod
186+
def create(cls, *children, **props):
187+
on_events = props.pop("on_events", {})
188+
189+
event_chains = {}
190+
for event_name, handler in on_events.items():
191+
# Convert the EventHandler/EventSpec/lambda to an EventChain
192+
event_chains[event_name] = rx.EventChain.create(
193+
handler,
194+
args_spec=rx.event.no_args_event_spec,
195+
key=event_name,
196+
)
197+
if on_events:
198+
props["on_events"] = event_chains
199+
200+
# Create the component instance
201+
return super().create(*children, **props)
157202
```

0 commit comments

Comments
 (0)