Issue with Input Focus Loss on Row Updates in React Table #5877
Replies: 2 comments
-
I know that there is a demo for editable cells: |
Beta Was this translation helpful? Give feedback.
-
I've encountered this issue in my own work and came up with an ok solution. For me, I was using a hand-rolled solution, which for your use case might mean needing to compose a component around Mantine's NumberInput in order to get this to work. But here's the crux of it: Assuming you're using the latest TanStack API, the columnHelper (createColumnHelper()) accessor will be needed (but you can still make it work with older versions). When defining your columns to mirror the data, you can control which cells render which component. So in a basic example you might have a table of persons, where one row of the table would correspond to an item in your dataset, [...., {name: "John Doe", age: 44}...] using the columnHelper.accessor you could have something like this when defining your columns
To control restoring the focus to the cell component after the re-render I used the metadata available from the (info) passed to each cell by TanStackTable. Specifically, info.column.id (the column name) and info.row.index (the row index). Passing these in as props to my individual cell components then allowed me to evaluate whether my cell that just triggered the re-render needs to have it's focus restored. Here is the code that shows the props passed
Then from within the cell component I use a useEffect to compare the ref that is passed in (focusRef) with the colName and rowIdx and then use the ref that is set on the cell component to call focus() I was controlling the state of my cell before calling setData to update my table state, so housing the focus logic in a useEffect or useLayoutEffect minimizes the excessive calls (not showing all the code for brevity sake)
Then the final piece of the puzzle is to set the focusRef.current to have the colName and rowIdx onFocus and to reset it to an empty object onBlur. It works pretty good for me, hope this helps! |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I’m currently facing an issue with input focus in a dynamic table that uses React Table (@tanstack/react-table) along with Mantine UI for editable fields. Specifically, I’m encountering an issue where the input field (e.g., NumberInput from Mantine) loses focus after a row update or re-render.
Issue Details
In my table, each row contains a NumberInput component where users can update the value. After a user updates the value, I need the input to retain focus
Beta Was this translation helpful? Give feedback.
All reactions