Function freya_hooks::use_focus

source ·
pub fn use_focus() -> UseFocus
Expand description

Create a focus manager for a node.

With this you can focus this node whenever you want or subscribe to any focus change, this way you can style your element based on its focus state.

§Simple example

fn app() -> Element {
    // Create a focus instance
    let mut my_focus = use_focus();

    rsx!(
        rect {
            // Bind the focus to this `rect`
            a11y_id: my_focus.attribute(),
            // This will focus this element and effectively cause a rerender updating the returned value of `is_focused()`
            onclick: move |_| my_focus.focus(),
            label {
                "Am I focused? {my_focus.is_focused()}"
            }
        }
    )
}

§Style based on state

fn app() -> Element {
    let mut my_focus = use_focus();

    let background = if my_focus.is_focused() {
        "red"
    } else {
        "blue"
    };

    rsx!(
        rect {
            background,
            a11y_id: my_focus.attribute(),
            onclick: move |_| my_focus.focus(),
            label {
                "Focus me!"
            }
        }
    )
}

§Keyboard navigation

Elements can also be selected with the keyboard, for those cases you can also subscribe by calling UseFocus::is_focused_with_keyboard.

fn app() -> Element {
    let mut my_focus = use_focus();

    let background = if my_focus.is_focused_with_keyboard() {
        "red"
    } else {
        "blue"
    };

    rsx!(
        rect {
            background,
            a11y_id: my_focus.attribute(),
            label {
                "Focus me!"
            }
        }
    )
}