This is my code where I get a reference to the current element that I want to focus on, but the focus does not go to that 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]);
This is also how I reference the input element I want to focus on.
{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 also tried using useLayoutEffect, but without success. In the console I get the correct input element that 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>
Your
useEffect
needs to depend onbarcodeRef
, as shown below: