Reputation: 34013
With the code below, taken from this SO answer, a user can select cells vertically in a grid by click-and-drag.
I intend to use this functionality in React and thus need to convert it to a component.
How would one change the method-chaining and selector based structure to React?
--HTML--
<table cellpadding="0" cellspacing="0" id="our_table">
<tr>
<td data-row="1" data-col="1">a</td>
<td data-row="1" data-col="2">b</td>
<td data-row="1" data-col="3">c</td>
</tr>
<tr>
<td data-row="2" data-col="1">d</td>
<td data-row="2" data-col="2">e</td>
<td data-row="2" data-col="3">f</td>
</tr>
<tr>
<td data-row="3" data-col="1">g</td>
<td data-row="3" data-col="2">h</td>
<td data-row="3" data-col="3">i</td>
</tr>
</table>
--CSS--
table td {
width:100px;
height:100px;
text-align:center;
vertical-align:middle;
background-color:#ccc;
border:1px solid #fff;
}
table td.highlighted {
background-color:#999;
}
--jQuery--
$(function () {
var isMouseDown = false,
isHighlighted;
var currentCol;
$("#our_table td")
.mousedown(function () {
isMouseDown = true;
currentCol = this.getAttribute("data-col");
$(this).toggleClass("highlighted");
isHighlighted = $(this).hasClass("highlighted");
return false; // prevent text selection
})
.mouseover(function () {
if (isMouseDown) {
if(currentCol === this.getAttribute("data-col")){
$(this).toggleClass("highlighted", isHighlighted);
}
}
})
.bind("selectstart", function () {
return false;
})
$(document)
.mouseup(function () {
isMouseDown = false;
});
});
Upvotes: 1
Views: 196
Reputation: 606
All what you need is in React Event System docs. onMouseDown, onMouseUp and onMouseOver are the most interesting event handlers for you. I created Similar Example.
In componentWillReceiveProps
function I check if the cell should update their own state and I use shouldComponentUpdate
to prevent rendering the component if it's not needed (it's very important when you have a lot of cells). The main state is in Hello
(parent) component: overId
contains cell data, startedId
contains starting cell and enableSelect
is true when we start selection.
It's "similar" because I didn't check your example carefully, but I think it's good enough to show you how it's works.
Upvotes: 1