Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
83fd080
Add env, the API scripts reach Reflex through
FarhanAliRaza Nov 20, 2026
5dd9697
Format script_env.js with biome
FarhanAliRaza Nov 20, 2026
20fc39d
Add docstrings to the script env tests
FarhanAliRaza Nov 20, 2026
2c92b05
Rename the script API to reflex and keep env.json in scripts
FarhanAliRaza Nov 21, 2026
e95f417
Put ref, add_events and library directly on rx.js
FarhanAliRaza Nov 21, 2026
4ae5dbc
Test reflex and rx.js end to end in the call_script app
FarhanAliRaza Nov 21, 2026
2557adf
Document reflex and rx.js usage-first
FarhanAliRaza Nov 21, 2026
b35a13e
Reject library names the registry only inherits, and correct the refl…
FarhanAliRaza Nov 22, 2026
8901c28
Drop rx.js.add_events, which only repeats an event trigger
FarhanAliRaza Nov 23, 2026
f2e95f3
Drop reflex.library and rx.js.library, which nothing needs
FarhanAliRaza Nov 24, 2026
fa329da
Merge remote-tracking branch 'upstream/main' into farhan/focused-darw…
FarhanAliRaza Nov 24, 2026
eb98b8b
Merge remote-tracking branch 'upstream/main' into farhan/focused-darw…
FarhanAliRaza Nov 25, 2026
c4c7a5e
docs: show how to get an event handler's full name for reflex.event
FarhanAliRaza Nov 26, 2026
e771062
docs: note reflex.ref is undefined for a component with a Var id
FarhanAliRaza Nov 26, 2026
46b4462
Restore eventLoop.addEvents after reflex tests; list js last in _SUBM…
FarhanAliRaza Nov 26, 2026
c356643
docs: fix the wording of the handler full name warning
FarhanAliRaza Nov 26, 2026
3482137
docs: import the local component example by its importable path
FarhanAliRaza Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
148 changes: 148 additions & 0 deletions docs/api-reference/browser_javascript.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,154 @@ The `callback` parameter may be an `EventHandler` with one argument, or a lambda
If the callback is None, then no event is triggered.
```

## Reaching Reflex from JavaScript

JavaScript you run in the browser reaches Reflex through `reflex`, an object
whose members stay the same across Reflex versions:

| Member | What it does |
| --- | --- |
| `reflex.ref(id)` | The ref of the component with that `id`. `undefined` until a component with that `id` renders, and always for a component whose `id` is a var, which registers no ref; its `current` is `null` until React attaches the element, then the element. |
| `reflex.addEvents(events)` | Dispatch events, as an event trigger does. |
| `reflex.event(name, payload)` | Build an event for `reflex.addEvents`: `name` is the event handler's full name, `payload` its arguments by name. |

An event handler's full name encodes the module and class of its state, and its
format may change between Reflex versions, so never write one out by hand.
Build it in Python, as `f"{State.get_full_name()}.handler_name"`, and pass it
into the JavaScript.

Prefer `reflex` over the other names a script can see, such as `refs`,
`ReflexEvent` or `addEvents`: those are internals of the frontend and may change
between Reflex versions.

In a script, `reflex` and `env` (the app's config, which `rx.get_upload_url`
reads) name these values, so a global of the same name on your page is
reachable only as `window.reflex` or `window.env`.

### From a Script

Code run by `rx.call_script` sees `reflex`:

```python demo exec
class ReflexApiState(rx.State):
result: str = ""

@rx.event
def set_result(self, result: str):
self.result = result


def reflex_api_demo():
return rx.vstack(
rx.input(id="reflex_api_search", placeholder="Type something"),
rx.hstack(
rx.button(
"Read",
on_click=rx.call_script(
"reflex.ref('reflex_api_search').current.value",
callback=ReflexApiState.set_result,
),
),
rx.button(
"Send",
on_click=rx.call_script(
"reflex.addEvents([reflex.event("
f"'{ReflexApiState.get_full_name()}.set_result', "
"{result: reflex.ref('reflex_api_search').current.value})])"
),
),
),
rx.text(f"Result: {ReflexApiState.result}"),
)
```

To focus, blur, set or scroll to a component, use the events that already do
it: `rx.set_focus(id)`, `rx.blur_focus(id)`, `rx.set_value(id, value)` and
`rx.scroll_to(id)`.

### From a JavaScript Module

A JavaScript module, such as a [local component](/docs/wrapping-react/local-packages/),
imports `reflex` from `$/utils/reflex`. This one sends the value of the input
with `id="search"` to the event handler named by its `handlerName` prop:

```javascript
// search_saver.jsx
import { reflex } from "$/utils/reflex";

export function SearchSaver({ handlerName }) {
const save = () => {
const value = reflex.ref("search").current.value;
reflex.addEvents([reflex.event(handlerName, { value })]);
};
return <button onClick={save}>Save</button>;
}
```

The Python side passes the handler's full name as that prop:

```python
search_saver_path = rx.asset("./search_saver.jsx", shared=True)


class SearchSaver(rx.Component):
library = search_saver_path.importable_path
tag = "SearchSaver"

# The full name of the event handler to send the value to.
handler_name: rx.Var[str]


class SavedState(rx.State):
saved: str = ""

@rx.event
def save(self, value: str):
self.saved = value


def saved_search():
return rx.vstack(
rx.input(id="search"),
SearchSaver.create(handler_name=f"{SavedState.get_full_name()}.save"),
rx.text(SavedState.saved),
)
```

### From Python

`rx.js.ref(id)` builds `reflex.ref(id)` from Python. It returns a var, which
`rx.run_script` runs whether an event trigger uses it or an event handler
returns it:

```python
class SearchState(rx.State):
query: str = ""

@rx.event
def set_query(self, query: str):
self.query = query

@rx.event
def read_search(self):
# Read the input's current value from the browser.
return rx.run_script(
rx.js.ref("search").current.value, callback=SearchState.set_query
)


def search():
return rx.vstack(
rx.input(id="search"),
rx.button("Read", on_click=SearchState.read_search),
rx.text(SearchState.query),
)
```

Python has no `reflex.addEvents`: dispatch events from Python as usual, with an
event trigger or by returning them from an event handler. `reflex.addEvents` is
for JavaScript that sends a value it computed back to Python.

## Using React Hooks

To use React Hooks directly in a Reflex app, you must subclass `rx.Component`,
Expand Down
1 change: 1 addition & 0 deletions news/+reflex-js.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add `rx.js.ref(id)`, a var that reads a component's ref through the browser's `reflex` API from Python, e.g. `rx.run_script(rx.js.ref("search").current.value, callback=State.set_query)`. See [Reaching Reflex from JavaScript](https://reflex.dev/docs/api-reference/browser-javascript/#reaching-reflex-from-javascript).
Original file line number Diff line number Diff line change
@@ -1 +1 @@
Shrink the shared JavaScript chunk by about 88 KB (11 KB gzipped) when `frontend_lazy_bundled_libraries` is on: server-provided scripts and callbacks no longer use a direct `eval`, so the minifier can shorten every name in that chunk. Scripts passed to `rx.call_script` and `rx.call_function` still see every export of `utils/state.js` (such as `ReflexEvent`, `refs` and `queueEvents`), plus `addEvents`, `socket`, `navigate`, `params`, `token` and the globals; names the module does not export, such as its imports, are no longer in scope.
Shrink the shared JavaScript chunk by about 88 KB (11 KB gzipped) when `frontend_lazy_bundled_libraries` is on: server-provided scripts and callbacks no longer use a direct `eval`, so the minifier can shorten every name in that chunk. Scripts passed to `rx.call_script` and `rx.call_function` still see every export of `utils/state.js` (such as `ReflexEvent`, `refs` and `queueEvents`), plus `addEvents`, `socket`, `navigate`, `params`, `token`, `env` (which `rx.get_upload_url` reads), `reflex` and the globals; names the module does not export, such as its other imports, are no longer in scope.
1 change: 1 addition & 0 deletions packages/reflex-base/news/+reflex-js.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add `reflex`, the API browser JavaScript reaches Reflex through: `rx.call_script` code, and JavaScript modules through `import { reflex } from "$/utils/reflex"`, can call `reflex.ref(id)`, `reflex.addEvents(events)` and `reflex.event(name, payload)` instead of frontend internals, e.g. `rx.call_script("reflex.ref('search').current.value", callback=State.set_query)`. See [Reaching Reflex from JavaScript](https://reflex.dev/docs/api-reference/browser-javascript/#reaching-reflex-from-javascript).
2 changes: 2 additions & 0 deletions packages/reflex-base/src/reflex_base/constants/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ class Dirs(SimpleNamespace):
CONTEXTS_PATH = UTILS + "/context"
# The name of the client state file.
CLIENT_STATE_PATH = UTILS + "/client_state"
# The module defining `reflex`, the API JavaScript reaches Reflex through.
REFLEX_API_PATH = UTILS + "/reflex"
# The name of the output directory.
BUILD_DIR = "build"
# The name of the static files directory.
Expand Down
55 changes: 55 additions & 0 deletions packages/reflex-base/src/reflex_base/js.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""Build calls on ``reflex``, the API browser code reaches Reflex through.

The frontend defines ``reflex`` in ``utils/reflex.js``. Each function here
returns a Var that renders as a call on it, such as ``reflex.ref("search")``.
A page that uses one imports ``reflex``, and code ``rx.run_script`` sends from
the backend has ``reflex`` in scope, so the same Var works in both.
"""

from __future__ import annotations

from collections.abc import Mapping
from typing import Any

from reflex_base.constants.base import Dirs
from reflex_base.utils.imports import ImportVar
from reflex_base.vars.base import Var, VarData
from reflex_base.vars.function import FunctionVar
from reflex_base.vars.object import ObjectVar

__all__ = ["ref"]

_REFLEX_VAR_DATA = VarData(
imports={f"$/{Dirs.REFLEX_API_PATH}": [ImportVar(tag="reflex")]}
)


def _call(member: str, *args: Any) -> Var:
"""Call a member of ``reflex``.

Args:
member: The member's name.
*args: The arguments to call it with.

Returns:
The call.
"""
return (
Var(_js_expr=f"reflex.{member}", _var_data=_REFLEX_VAR_DATA)
.to(FunctionVar)
.call(*args)
)


def ref(id: str | Var[str]) -> ObjectVar[Mapping[str, Mapping[str, Any]]]:
"""Get the ref of a component by its id.

Args:
id: The component's id.

Returns:
The ref, whose ``current`` is the mounted element, or undefined if no
component with that id has mounted or the component's id is a Var,
which registers no ref.
"""
return _call("ref", id).to(ObjectVar, Mapping[str, Mapping[str, Any]])
10 changes: 6 additions & 4 deletions packages/reflex-frontend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,12 @@ without it appearing in its arguments. What there is, and where it is pinned:
callbacks) runs through `runScript` in `utils/state.js`, which compiles it
with the Function constructor and passes in every export of that module, the
late-bound `addEvents`, the `socket`, `navigate` and `params` of the event
being applied, and the session `token`. A direct `eval` would see every
module local, but it stops the minifier from mangling the chunk that holds
it. So a script sees those names and the globals, and nothing else. Renaming
an export changes what compiled callbacks can call.
being applied, the session `token`, `env` (the app's `$/env.json`, which
`rx.get_upload_url` compiles to) and `reflex` (the API in `utils/reflex.js`,
which `rx.js` compiles to). A direct `eval` would see every module local, but
it stops the minifier from mangling the chunk that holds it. So a script sees
those names and the globals, and nothing else. Renaming an export changes
what compiled callbacks can call.
- **Globals the runtime reads**: hooks other code installs on `window`
(`__reflex_otel`, `__reflex`, `__reflex_load`) and the per-app `$/env.json`.
Each is declared in `types/globals.d.ts`; reading one that is not fails the
Expand Down
46 changes: 46 additions & 0 deletions packages/reflex-frontend/src/utils/reflex.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// `reflex`: the API JavaScript run by an app reaches Reflex through, in place
// of the internals of utils/state.js. `rx.call_script` code sees it as
// `reflex`, a module imports it from here, and `rx.js` builds calls on it from
// Python. Its members read the runtime at call time, so it is safe to import
// before the event loop mounts and from a module utils/state.js imports.
import { eventLoop } from "$/utils/context-registry";
import { ReflexEvent, refs } from "$/utils/state";

/**
* Get the name a component id is registered under in `refs`.
*
* Mirrors `format_ref` in reflex_base.utils.format: every run of characters
* that are not letters, digits or underscores becomes one underscore.
* @param {string} id The component id.
* @returns {string} The registry key.
*/
const refName = (id) => `ref_${String(id).replace(/[^\p{L}\p{N}_]+/gu, "_")}`;

export const reflex = Object.freeze({
Comment thread
FarhanAliRaza marked this conversation as resolved.
Resolved
/**
* Get the ref of a component by its id.
* @param {string} id The component id.
* @returns {{current: any} | undefined} The ref, or undefined if no
* component with that id has rendered or the component's id is a Var,
* which registers no ref. Its `current` is null until React attaches the
* element.
*/
ref: (id) => refs[refName(id)],

/**
* Dispatch events through the mounted event loop, as event triggers do.
* @param {any[]} events The events, built with `reflex.event`.
*/
addEvents: (events) => {
eventLoop.addEvents(events);
},

/**
* Build an event for `addEvents`.
* @param {string} name The full name of the event handler, built in Python
* as `f"{State.get_full_name()}.handler_name"` and passed in.
* @param {object} [payload] The handler's arguments, by name.
* @returns {any} The event.
*/
event: (name, payload = {}) => ReflexEvent(name, payload),
});
18 changes: 13 additions & 5 deletions packages/reflex-frontend/src/utils/state.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
import { app, eventLoop } from "$/utils/context-registry";
// This module's own exports, passed to server-provided scripts by runScript.
import * as stateExports from "$/utils/state";
import { reflex } from "$/utils/reflex";
import {
CLIENT_STATE_REF,
getClientState,
Expand Down Expand Up @@ -584,11 +585,14 @@ function urlFrom(string) {
* Callback strings and `rx.call_script` code reference helpers compiled
* pages import from here (`ReflexEvent`, `pyMod`, `isTrue`, ...), and apps
* written against the former direct eval also use `socket`, `navigate`,
* `params` and `token`. A direct eval would see them, but it also stops the
* minifier from mangling every name in the chunk that holds it, so the code
* is compiled with the Function constructor and those names are passed in as
* parameters. The eval inside the body still runs the code as a strict
* script, so statements keep their completion value.
* `params` and `token`. Scripts reach Reflex through `reflex`, and
* `rx.get_upload_url` compiles to `getBackendURL(env.UPLOAD)`, which reads
* `env` from `$/env.json` as the former direct eval did. A direct eval would
* see these names, but it also stops the minifier from mangling every name in
* the chunk that holds it, so the code is compiled with the Function
* constructor and the names are passed in as parameters. The eval inside the
* body still runs the code as a strict script, so statements keep their
* completion value.
*
* Compiled on first use: a Content Security Policy without `unsafe-eval`
* rejects the Function constructor, and apps that never send scripts must
Expand All @@ -610,6 +614,8 @@ const runScript = (code, addEvents, socket, navigate, params) => {
"navigate",
"params",
"token",
"env",
"reflex",
"code",
'"use strict"; return eval(code);',
);
Expand All @@ -620,6 +626,8 @@ const runScript = (code, addEvents, socket, navigate, params) => {
navigate,
params,
token,
env,
reflex,
code,
);
};
Expand Down
1 change: 1 addition & 0 deletions packages/reflex-frontend/tests/public_api.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ const PUBLIC_API = {
"useStateContext",
],
"$/utils/react-theme": ["ThemeProvider", "useTheme"],
"$/utils/reflex": ["reflex"],
"$/utils/helpers/array": ["default"],
"$/utils/helpers/datetime": ["default"],
"$/utils/helpers/debounce": ["default"],
Expand Down
Loading
Loading