leptos_use

Function use_mouse

Source
pub fn use_mouse() -> UseMouseReturn
Expand description

Reactive mouse position

§Demo

Link to Demo

§Basic Usage

let UseMouseReturn {
    x, y, source_type, ..
} = use_mouse();

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.

let UseMouseReturn {
    x, y, ..
} = use_mouse_with_options(
    UseMouseOptions::default().touch(false)
);

§Custom Extractor

It’s also possible to provide a custom extractor to get the position from the events.

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 Signals with the initial_values.