I believe the text field is losing focus because the entire table is being re-rendered when the state updates. I’ve updated the code below, adding a key to maintain focus and optimising the state update:
import TableContainer from "@mui/material/TableContainer";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableRow from "@mui/material/TableRow";
import TableCell from "@mui/material/TableCell";
import TextField from "@mui/material/TextField";
import { styled } from "@mui/system";
import { useState } from "react";
export default function TableTextFieldTest() {
const [questions, setQuestions] = useState([
{
index: 0,
question: "Do you have any feedback on your manager or team that you'd like to share?",
},
{
index: 1,
question: "What suggestions do you have for improving the company culture or work environment?",
},
{
index: 2,
question: "How was your experience working here?",
}
]);
const TableBodyCell = styled(TableCell)({
paddingLeft: "24px",
paddingRight: "24px",
paddingTop: "16px",
paddingBottom: "16px"
});
function handleEditTextfield(e, index) {
setQuestions(prevQuestions =>
prevQuestions.map(q =>
q.index === index ? { ...q, question: e.target.value } : q
)
);
};
return (
<TableContainer>
<Table>
<TableBody>
{questions
.sort((q1, q2) => q1.index - q2.index)
.map((q) => (
<TableRow key={q.index}>
<TableBodyCell>
<TextField
value={q.question}
onChange={(e) => handleEditTextfield(e, q.index)}
sx={{ width: "100%" }}
/>
</TableBodyCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
);
};
Changes made are:
key
prop to the TableRow
component using q.index
handleEditTextfield
to use the functional update pattern with prevQuestions
handleEditTextfield
to use q.index
instead of the map indexThe above changes should maintain focus on the text field while editing. The problems with the original code were:
This should, hopefully, resolve the issue.