I have created a table when a user uploads a csv file. This file gets sent to backend to process and return the data with a prefix of: 'ERROR:' to spot the errors in my table.
So when a cell contains the word 'ERROR:' this cell will be highlighted in red and contain an input to fix this error.
This is the Cells element I render into react table and my state as well:
const initialHoverError = {
rowIndex: 0,
cellName: '',
errorMessage: ''
}
const [hoverError, setHoverError] = useState(initialHoverError)
const Cells = ({row}) => useMemo(() => {
const { original } = row
return row.cells.map(cell => {
const { column } = cell
const { id: cellIndex } = column
const { rowIndex, cellName, errorMessage } = hoverError
const hasError = checkError(original[cellIndex])
return (
<Table.Td
{...cell.getCellProps()}
className={cn(styles.Cell, { [styles.HasError]: hasError })}
onMouseEnter={() =>
handleHoverError('active', row.id, cellIndex, original[cellIndex])
}
onMouseLeave={() => handleHoverError()}
>
{hasError ? (
<div>
<Text
className={cn(styles.ErrorText, {
[styles.ErrorVisible]:
cellIndex === cellName && row.id + 1 === rowIndex + 1
})}
>
{errorMessage}
</Text>
<input
className={styles.ErrorInput}
onBlur={event => handleErrorUpdate(event, cellIndex, row.id)}
/>
</div>
) : (
cell.render('Cell')
)}
</Table.Td>
)
}) }, [data])
This is the function that allows me to hover over the cells containing an error and displaying it to the user.
const handleHoverError = (type, rowIndex, cellIndex, text) => {
const hasError = checkError(text)
if (type === 'active' && hasError) {
setHoverError({
rowIndex,
cellName: cellIndex,
errorMessage: text.slice(6)
})
return
}
return setHoverError(initialHoverError)
}
So the issue that I am having is that everytime my mouse leaves the td(onMouseLeave) the my input field loses focus and rerenders(clears). So when I have typed something into an input and the mouse leaves the td element the input is blank and out of focus.
And finally this is how I update my input field. When this hover functionality is removed everything works perfectly.
const handleErrorUpdate = (event, cellIndex, rowIndex) => {
event.preventDefault()
const newData = [...data]
if (event.target.value !== '')
newData[rowIndex][cellIndex] = event.target.value
setData(newData)
}
Please give me some advice.