react-data-grid icon indicating copy to clipboard operation
react-data-grid copied to clipboard

Deselect cell

Open Lior-Dolev opened this issue 5 years ago • 5 comments

Is there a way to deselect a cell? I'd like to be able to lose focus on a cell.

For example if I have a selected cell and then I click on a column's header for sorting then I want to deselect the previous cell and the next time a user will use Tab then cell (0,0) will be focused.

I tried to reset cell values (rowIdx: -1, idx: -1) but since it's out of boundaries my selection is not applied.

Lior-Dolev avatar Aug 17 '20 07:08 Lior-Dolev

I am also having the same problem, any solution?

matheusroversi avatar Sep 02 '20 13:09 matheusroversi

I couldn't find an existing solution. I added that feature and I'm waiting for my pull request to be reviewed & approved.

You can take a look at it here: https://github.com/adazzle/react-data-grid/pull/2121 Basically I just added a deselectCell() function to the ref API.

Lior-Dolev avatar Sep 06 '20 05:09 Lior-Dolev

A simple way that worked for me in version In v7.0.0-alpha.0 without changing the component was

constructor() {
    this.refGrid = React.createRef()
}

deselectGrid() {
    this.refs.grid.selectStart(-1)
    ...
}

I hope to help someone

matheusroversi avatar Oct 16 '20 20:10 matheusroversi

It is a tricky issue, the workaround I made for my case is to issue a click event on the next cell, it may or may not be useful for your case, you can use a hidden element/cell to capture the focus if needed.

Just FYI - click next cell to deselect current cell:

        const p = getParentByClass(anchor.current, 'rdg-cell');
        (p?.nextSibling as HTMLElement)?.click();

shawncao avatar Mar 03 '23 19:03 shawncao

I have a similar requirement and found this works quite well for going to a specific cell, or deselected all:

...

const rdgRef = useRef(null)

useImperativeHandle(ref, () => ({
  goTo: (position) => {
    rdgRef.current?.scrollToCell(position)
    rdgRef.current?.selectCell(position, { shouldFocusCell: true })
  },
  deselectAll: () => {
    rdgRef.current?.element?.blur()
    rdgRef.current?.selectCell({ idx: 0, rowIdx: -1 })
  },
}), [])

return <ReactDataGrid ref={rdgRef} />

subblue avatar Nov 08 '25 12:11 subblue