I'm building a table with React and Material UI 5, but I have a problem with the input when I'm writing. The input loses the focus in each character digited.
How can I handle with component re-rendering?
The complete code: https://codesandbox.io/s/mytable-rn98b
CodePudding user response:
You are defining new component types in the middle of rendering MyTable. Every time MyTable renders, you define a new TableToolbar, new HeaderList, new RowList, new CellList, new CellEdit. These functions may have the same text as the previous ones, but they do not pass a reference equality check (===
) with their previous incarnations, so they are different types of components to react. Since they are different types, react must unmount the old ones and mount the new ones, which wipes out their state and focus.
If you want these to be their own components, they need to be defined just once, outside of the main component. This will require a bit of rewriting, since you can no longer rely on closure variables to access MyTable's data. Instead, pass the needed data as props.
For example, CellList should change from this:
const CellList = ({ row }) =>
headers.map((header) => (
<TableCell key={header.prop}>{row[header.prop]}</TableCell>
));
To this (and make sure to move it outside of MyTable):
const CellList = ({ row , headers }) => {
return (
<>
{headers.map((header) => (
<TableCell key={header.prop}>{row[header.prop]}</TableCell>
))}
<>
)
}