Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to selected a range cells with mouse in react?

I am building a table with reactjs. So I want to when a user clicks a cell and hold moves to another cell. The cells between have to highlight. I do it with DOM selector. And I think it a not the right way to react. So how I can do it without DOM SELECTOR

Here my code with dom select:

import React, {useState} from "react";
import './Style.css';

export default function Table() {
    const [cell, setCell] = useState([]);
    let div = [];

    let selecting, start, end;

    let beginSelection = i => {
        selecting = true;
        start = i;
        updateSelection(i);
    };

    let endSelection = (i = end) => {
        selecting = false;
        updateSelection(i);
    };

    let updateSelection = i => {
        if (selecting)
            end = i;
        [...document.querySelectorAll('span')].forEach((span, i) =>
            span.classList.toggle('selected', i >= start && i <= end || i >= end && i <= start));
    };



    for(let i = 0; i < 31; i++) {
        let a = <span key={i} onMouseDown={()=>beginSelection(i)} onMouseUp={()=>endSelection(i)} onMouseMove={()=>updateSelection(i)}>{i}</span>;

        div.push(a);
        cell.push(a);
    }


    return div;
}

here is my demo: https://codesandbox.io/s/github/Kalipts/hover please help. Thanks

like image 743
kalipts Avatar asked Oct 24 '25 15:10

kalipts


1 Answers

using state & className for cell element

className={ (end <= i && i <= start) || (start <= i && i <= end) ? "selected" : "" }

https://codesandbox.io/s/ecstatic-driscoll-r8649

like image 128
Rkv88 - Kanyan Avatar answered Oct 26 '25 04:10

Rkv88 - Kanyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!