Skip to content
Advertisement

React table cell getSelection()

I have a table with an onRowClick handler on the <tr/> element, I want to prevent a click event if I select text inside it, my solution was this:

const getSelectionWithoutClick = (originalHandler: () => void) => {
  if (!getSelection()?.toString()) originalHandler();
};

What I found odd is, when I select a text inside a cell, and click on the same cell, the click event is not fired until the selection is cleared, but if click on another cell (even in the same row), while text is selected in the original cell, the click event fires. You know why this happens??

Advertisement

Answer

I think you can differentiate between click and select event based on onMouse up

function TablePage() {
  function onSelect(e) {
    let selection = window.getSelection().toString();

    if (selection === '') {
      console.log('click');
    } else {
      console.log('selection', selection);
    }
  }

  return <table>
    <thead>
      <tr>
        <th>Company</th>
        <th>Contact</th>
        <th>Country</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td onMouseUp={onSelect}>Alfreds Futterkiste</td>
        <td onMouseUp={onSelect}>Maria Anders</td>
        <td onMouseUp={onSelect}>Germany</td>
      </tr>
    </tbody>
  </table>
}

export default TablePage; 
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement