0

I'm working on a web application using the reflex library, and I'm trying to implement a feature where a function is executed when the user presses the Enter key in an input field. Specifically, I have an Input component, and I want to trigger a search function when the user presses Enter.

Here's what I've tried so far:

# My State class
class State(rx.State):
    # ... (other state variables)

    def handle_key_press(self, event):
        if event.type_ == 'key_down' and event.key == 'Enter':
            self.handle_search()

# My Input component
rx.input(
    placeholder="Search here...",
    on_key_down=State.handle_key_press,
)

However, I'm encountering an error, and the function is not being triggered as expected. I've checked the documentation, but I couldn't find detailed information on the structure of the event object returned by the on_key_down event.

Could someone please provide me with more information on the structure of the event object returned by the on_key_down event trigger? Specifically, what properties should I be checking to determine if the Enter key was pressed? Additionally, if there's a better way to achieve this functionality in the reflex library, I'd greatly appreciate any guidance.

Thank you for your help!

2 Answers 2

0

Just the if statement was wrong.

Also important to mention that you would have to user return when calling an existing function. For example when using a search box either bei pressing enter or clicking a button the same search function is called.

# ---------- state.py ----------
class State(rx.State):
    def search(self):
        # Search logic
        pass
    
    def search_on_key_down(self, event):
        if event.key == "Enter":
            return self.search()



# ---------- myapp.py ----------

# Input field with the possibility to search with Enter
rx.input(
    placeholder="Search here...",
    on_key_down=State.search_on_key_down,
)

# Button to search
rx.button(
    "Search",
    on_click=State.search,
)
0

At least in the Reflex version 0.2.6, you get the key directly in the event variable as a string. So, your code should look like this:

# My State class
class State(rx.State):
    # ... (other state variables)

    def handle_key_press(self, event):
        if event == 'Enter':
            self.handle_search()

# My Input component
rx.input(
    placeholder="Search here...",
    on_key_down=State.handle_key_press,
)

Not the answer you're looking for? Browse other questions tagged or ask your own question.