use_mouse
Reactive mouse position
Demo
Basic Usage
use leptos::*;
use leptos_use::{use_mouse, UseMouseReturn};
#[component]
fn Demo() -> impl IntoView {
let UseMouseReturn {
x, y, source_type, ..
} = use_mouse();
view! { }
}
Touch is enabled by default. To only detect mouse changes, set touch
to false
.
The dragover
event is used to track mouse position while dragging.
use leptos::*;
use leptos_use::{use_mouse_with_options, UseMouseOptions, UseMouseReturn};
#[component]
fn Demo() -> impl IntoView {
let UseMouseReturn {
x, y, ..
} = use_mouse_with_options(
UseMouseOptions::default().touch(false)
);
view! { }
}
Custom Extractor
It's also possible to provide a custom extractor to get the position from the events.
use leptos::*;
use leptos::html::Div;
use web_sys::MouseEvent;
use leptos_use::{use_mouse_with_options, UseMouseOptions, UseMouseReturn, UseMouseEventExtractor, UseMouseCoordType};
#[derive(Clone)]
struct MyExtractor;
impl UseMouseEventExtractor for MyExtractor {
fn extract_mouse_coords(&self, event: &MouseEvent) -> Option<(f64, f64)> {
Some((event.offset_x() as f64, event.offset_y() as f64))
}
// don't implement fn extract_touch_coords to ignore touch events
}
#[component]
fn Demo() -> impl IntoView {
let element = create_node_ref::<Div>();
let UseMouseReturn {
x, y, source_type, ..
} = use_mouse_with_options(
UseMouseOptions::default()
.target(element)
.coord_type(UseMouseCoordType::Custom(MyExtractor))
);
view! { <div node_ref=element></div> }
}
Server-Side Rendering
On the server this returns simple Signal
s with the initial_value
s.
Feature
This function is only available if the crate feature
use_mouse
is enabled