Skip to content

Instantly share code, notes, and snippets.

@masenf
Created February 23, 2024 06:08
Show Gist options
  • Save masenf/7204aee4fbe1cb9ac4720bd8d6bfc2a4 to your computer and use it in GitHub Desktop.
Save masenf/7204aee4fbe1cb9ac4720bd8d6bfc2a4 to your computer and use it in GitHub Desktop.
reflex frontend slider
import reflex as rx
import reflex.components.radix.themes as rdxt
from reflex.components.component import MemoizationLeaf
from reflex.utils import imports
class State(rx.State):
val: int = 50
LOCAL_SLIDER_VALUE = "local_slider_value"
SET_LOCAL_SLIDER_VALUE = "set_local_slider_value"
LOCAL_SLIDER_VAR_DATA = rx.vars.VarData(
imports={"react": {imports.ImportVar(tag="useState")}},
hooks={f"const [{LOCAL_SLIDER_VALUE}, {SET_LOCAL_SLIDER_VALUE}] = useState(50);"},
)
LOCAL_SLIDER_VAR = rx.Var.create(LOCAL_SLIDER_VALUE)._replace(
_var_type=int,
merge_var_data=LOCAL_SLIDER_VAR_DATA,
)
LOCAL_SLIDER_ON_CHANGE = rx.Var.create(
f"e => {SET_LOCAL_SLIDER_VALUE}(e)"
)._replace(
_var_type=rx.EventChain,
merge_var_data=LOCAL_SLIDER_VAR_DATA,
)
class IntegralFragment(rx.Fragment, MemoizationLeaf):
"""All children of this component will be rendered as a single react component."""
def index() -> rx.Component:
return rx.fragment(
rx.color_mode_button(rx.color_mode_icon(), float="right"),
rx.vstack(
rx.heading(f"Backend Value: {State.val}"),
IntegralFragment.create(
rx.heading(f"Frontend Value: ${{{LOCAL_SLIDER_VAR}}}"),
rx.slider(
value=LOCAL_SLIDER_VAR,
on_change=LOCAL_SLIDER_ON_CHANGE,
on_change_end=State.set_val,
),
),
rx.match(
State.val,
(50, rx.button("50", on_click=State.set_val(75))),
(75, rx.button("75", on_click=State.set_val(100))),
(100, rx.button("100", on_click=State.set_val(50))),
rx.button("Other"),
),
rdxt.popover_root(
rdxt.popover_trigger(
rdxt.button("Comment", variant="soft"),
),
rdxt.popover_content(
rdxt.inset(
side="top",
background="url('https://source.unsplash.com/random/800x600') center/cover",
height="100px",
),
rdxt.box(
rdxt.textarea(placeholder="Write a comment…", style={"height": 80}),
rdxt.flex(
rdxt.flex(
rdxt.text(
rdxt.checkbox(),
rdxt.text("Send to group"),
as_="label",
size="2",
),
align="center",
gap="2",
as_child=True,
),
rdxt.popover_close(
rdxt.button("Comment", size="1")
),
gap="3",
mt="3",
justify="between",
),
pt="3",
),
style={"width": 360},
)
)
),
)
# Add state and page to the app.
app = rx.App()
app.add_page(index)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment