Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to (programmatically) select all cells, then copy? #303

Open
ericman314 opened this issue Sep 28, 2021 · 0 comments
Open

How to (programmatically) select all cells, then copy? #303

ericman314 opened this issue Sep 28, 2021 · 0 comments

Comments

@ericman314
Copy link

I will ask and answer my own question in the hopes it can be of use to someone, but I'm really hoping someone will share the right way to do this.

I have a ReactDataGrid with a controlled selection. I also have a custom copy handler, but I don't think that matters in this case.

<ReactDataGrid>
  data={myData}
  selected={mySelection}
  onSelect={setMySelection}
  handleCopy={handleCopy}
</ReactDataGrid>

I also have a "Select All" button outside of my ReactDataGrid, whose onClick handler calls this function to set the selection to the entire range:

function handleSelectAll() {
  setMySelection({ start: { i: 0, j: 0 }, end: { i: myData.length - 1, j: myData[0].length - 1 } })
} 

The problem is, after pressing the button, the "focus" in the table is lost and pressing Ctrl+C does nothing.

The only way I could get it to work was by dispatching mouse events to cells within the table, to simulate the user dragging across the entire table. This prevents the click on the "Select All" button from removing the Ctrl+C listener:

function handleSelectAll() {
  let topLeftElement = document.querySelector('table.data-grid > tbody > tr > td')
  topLeftElement.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }))

  let bottomRightElement = document.querySelector('table.data-grid > tbody > tr:last-child > td:last-child')
  setImmediate(() => bottomRightElement.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })))
  setImmediate(() => bottomRightElement.dispatchEvent(new MouseEvent('mouseup', { bubbles: true })))
} 

This is a no-good, horrible, very bad hack, so if anyone knows the correct way to do this I would be very glad to see it. In any case, thanks for this great library!

@ericman314 ericman314 changed the title How to select all cells, then copy? How to (programmatically) select all cells, then copy? Sep 28, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant