This is my code where I am getting the ref to the current element I want to focus but the focus isnt going to the element.
useEffect(() => {
setTimeout(() => {
console.log("This is current barcode ref inside", barcodeRef.current);
barcodeRef.current && barcodeRef.current.focus();
}, 500)
//barcodeRef.current && barcodeRef.current.focus();
}, [tableData]);
Also this is how I am referencing the input element which I want to focus.
{tableData.map((row, rowIndex) => (
<TableRow key={rowIndex}>
{columns.map(
(column) =>
!column.hidden && (
<TableCell
key={column.accessorKey}
style={{ width: column.width }}
>
{column.accessorKey === "ItemName" ? (
<Input
value={row[column.accessorKey] || ""}
onChange={(event) =>
handleLeaveItem(
rowIndex,
column.accessorKey,
event.target.value
)
}
/>
) : (
<Input
ref={column.accessorKey === "Barcode" ? barcodeRef : null}//reference to the input of barcode column in table row
value={row[column.accessorKey] || ""}
onChange={(event) =>
handleSaveCell(
rowIndex,
column.accessorKey,
event.target.value
)
}
/>
)}
</TableCell>
)
)}
<TableCell>
<IconButton onClick={() => handleRemoveRow(rowIndex)}>
<Delete />
</IconButton>
</TableCell>
</TableRow>
))}
I have tried using useLayoutEffect as well but didnt work. In the console I am getting this which is the correct Input element I want to focus on.
<div class="MuiInputBase-root MuiInput-root MuiInput-underline MuiInputBase-colorPrimary css-10tgus4-MuiInputBase-root-MuiInput-root">
::before
<input type="text" class="MuiInputBase-input MuiInput-input css-ume8vi-MuiInputBase-input-MuiInput-input" value>
::after
</div>
2
Answers
Your
useEffect
needs to depend of thebarcodeRef
like this:As you can see in your log, input is the child of the current stored element. So reference the input instead of the parent.