use_mouse
Reactive mouse position
Demo
Basic Usage
use leptos::prelude::*;
use leptos_use_mouse::{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::prelude::*;
use leptos_use_mouse::{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::prelude::*;
use leptos::html::Div;
use web_sys::MouseEvent;
use leptos_use_mouse::{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 = NodeRef::<Div>::new();
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
Make sure you follow the instructions in Server-Side Rendering.
On the server this returns simple Signals with the initial_values.
Installation
cargo add leptos-use-mouse
Options
UseMouseOptions
Options for use_mouse_with_options.
Every option is set with a builder method of the same name, e.g. UseMouseOptions::default().coord_type(...). See also the API docs.
coord_type
Type: UseMouseCoordType<Ex>
How to extract the x, y coordinates from mouse events or touches
target
Type: El
Listen events on target element. Defaults to window
touch
Type: bool
Listen to touchmove events. Defaults to true.
reset_on_touch_ends
Type: bool
Reset to initial value when touchend event fired. Defaults to false
initial_value
Type: Position
Initial values. Defaults to {x: 0.0, y: 0.0}.