Leptos-Use Guide

use_event_listener

Use EventListener with ease.

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

Usage

use leptos::prelude::*;
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::prelude::*;
use leptos::ev::click;
use leptos::logging::log;
use leptos_use::use_event_listener;

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

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

let (cond, set_cond) = 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::prelude::*;
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! { }
}

SendWrapped Return

The returned closure is a sendwrapped function. It can only be called from the same thread that called use_event_listener.

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