Reflex compiles your frontend code, defined as python functions, into a Javascript web application that runs in the user's browser. There are instances where you may need to supply custom javascript code to interop with Web APIs, use certain third-party libraries, or wrap low-level functionality that is not exposed via Reflex's Python API.
There are four ways to execute custom Javascript code into your Reflex app:
rx.script- Injects the script vianext/scriptfor efficient loading of inline and external Javascript code. Described further in the component library.- These components can be directly included in the body of a page, or they may
be passed to
rx.App(head_components=[rx.script(...)])to be included in the<Head>tag of all pages.
- These components can be directly included in the body of a page, or they may
be passed to
rx.call_script- An event handler that evaluates arbitrary Javascript code, and optionally returns the result to another event handler.
These previous two methods can work in tandem to load external scripts and then call functions defined within them in response to user events.
The following two methods are geared towards wrapping components and are described with examples in the Wrapping React section.
_get_hooksand_get_custom_codein anrx.ComponentsubclassVar.createwith_var_is_local=False
The rx.script component is the recommended way to load inline Javascript for greater control over
frontend behavior.
The functions and variables in the script can be accessed from backend event
handlers or frontend event triggers via the rx.call_script interface.
External scripts can be loaded either from the assets directory, or from CDN URL, and then controlled
via rx.call_script.
The rx.call_script function accepts a callback parameter that expects an
Event Handler with one argument which will receive the result of evaluating the
Javascript code. This can be used to access client-side values such as the
window.location or current scroll location, or any previously defined value.
Scroll Position: {}
window.location:
To use React Hooks directly in a Reflex app, you must subclass rx.Component,
typically rx.Fragment is used when the hook functionality has no visual
element. The hook code is returned by the add_hooks method, which is expected
to return a list[str] containing Javascript code which will be inserted into the
page component (i.e the render function itself).
For supporting code that must be defined outside of the component render
function, use _get_custom_code.
The following example uses useEffect to register global hotkeys on the
document object, and then triggers an event when a specific key is pressed.
Press a, s, d or w to trigger an event
Last watched key pressed:
This snippet can also be imported through pip: reflex-global-hotkey.