Leptos-Use Guide

on_click_outside

Listen for clicks outside of an element. Useful for modals or dropdowns.

Demo

Usage

use leptos::*;
use leptos::logging::log;
use leptos::html::Div;
use leptos_use::on_click_outside;

#[component]
fn Demo() -> impl IntoView {
let target = create_node_ref::<Div>();

on_click_outside(target, move |event| { log!("{:?}", event); });

view! {
    <div node_ref=target>"Hello World"</div>
    <div>"Outside element"</div>
}
}

This function uses Event.composedPath() which is not supported by IE 11, Edge 18 and below. If you are targeting these browsers, we recommend you to include this code snippet on your project.

Excluding Elements

Use this to ignore clicks on certain elements.

use leptos::*;
use leptos::logging::log;
use leptos::html::Div;
use leptos_use::{on_click_outside_with_options, OnClickOutsideOptions};

#[component]
fn Demo() -> impl IntoView {
let target = create_node_ref::<Div>();

on_click_outside_with_options(
    target,
    move |event| { log!("{:?}", event); },
    OnClickOutsideOptions::default().ignore(["input", "#some-id"]),
);

view! {
    <div node_ref=target>"Hello World"</div>
}
}

Server-Side Rendering

On the server this amounts to a no-op.

Types

Source

SourceDemoDocs