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
using state & className for cell element
className={
(end <= i && i <= start) || (start <= i && i <= end) ? "selected" : ""
}
https://codesandbox.io/s/ecstatic-driscoll-r8649
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With