I have modified the Selection with Keys example to work with React. However as soon as I press an arrow key, the app crashes in the code below:
const [gridApi, setGridApi] = useState<GridApi | undefined>();
const handleGridReady = (event: GridReadyEvent) => {
  setGridApi(event.api);
  setGridColumnApi(event.columnApi);
};
const keyboardNavigation = (params: NavigateToNextCellParams): CellPosition => {
    if (gridApi === undefined) {
        throw new Error('This should never happen!');
    }
    ...
};
I am setting gridApi using onGridReady before any keys are pressed (confirmed by adding a console.log). So I don't know how it is getting undefined.
My full source code is here.
 
                        
This is commonly known as stale closure in react hook. From my understanding here is what happen:
keyboardNavigationis registered only once at the first render.keyboardNavigationat that time references thegridApiinstance from the very first render which isundefined.AgGridReactin subsequent re-renders will use the firstkeyboardNavigationinstance, thus references the same oldgridApieven if it's been set now.You can verify that by logging the
gridApiin the render method, you can see from the second render, it has been initialized while your closurekeyboardNavigationstill references the stale instance ofgridApi.To fix that, you can change the code above to use reference instead of variable that can't be changed once baked in the closure.
Live Demo