Leptos-Use Guide

use_event_listener

Use EventListener with ease.

Register using addEventListener on mounted, and removeEventListener automatically on cleanup.

Usage

use leptos::*;
use leptos::ev::visibilitychange;
use leptos::logging::log;
use leptos_use::{use_document, use_event_listener};

#[component]
fn Demo() -> impl IntoView {
use_event_listener(use_document(), visibilitychange, |evt| {
    log!("{:?}", evt);
});
   view! { }
}

You can also pass a NodeRef as the event target, use_event_listener will unregister the previous event and register the new one when you change the target.

use leptos::*;
use leptos::ev::click;
use leptos::logging::log;
use leptos_use::use_event_listener;

#[component]
fn Demo() -> impl IntoView {
let element = create_node_ref();

use_event_listener(element, click, |evt| {
    log!("click from element {:?}", event_target::<web_sys::HtmlDivElement>(&evt));
});

let (cond, set_cond) = create_signal(true);

view! {
    <Show
        when=move || cond.get()
        fallback=move || view! { <div node_ref=element>"Condition false"</div> }
    >
        <div node_ref=element>"Condition true"</div>
    </Show>
}
}

You can also call the returned to unregister the listener.

use leptos::*;
use leptos::ev::keydown;
use leptos::logging::log;
use web_sys::KeyboardEvent;
use leptos_use::use_event_listener;

#[component]
fn Demo() -> impl IntoView {
let cleanup = use_event_listener(document().body(), keydown, |evt: KeyboardEvent| {
    log!("{}", &evt.key());
});

cleanup();

   view! { }
}

Server-Side Rendering

On the server this amounts to a noop.

Feature

This function is only available if the crate feature use_event_listener is enabled

Types

Source

SourceDemoDocs