I'm trying to create a custom MUI table that works with react-hook-form. The table rows have a checkbox to indicate whether an item is selected or not. My issue is I am able to "send" the data to the rows in order to correctly display the selected rows. However, I don't see a way to "retrieve" the data in the scenario that it changes.
My Table Body:
export default function HobbyList({ name, hobbies }: Props) {
const { control } = useFormContext();
const [selected, setSelected] = useState<Array<Hobby>>(hobbies);
return (
<Card>
<TableContainer>
<Table>
<Controller
name={name}
control={control}
render={({ field }) => {
console.log(selected);
console.log(field);
return (
<TableBody>
{apiHobbies.map((row, index) => {
console.log(row);
const selectedIds = selected.map((selected) => selected.id);
return (
<FieldRow
key={row.id}
row={row}
selected={selectedIds.includes(row.id)}
></FieldRow>
);
})}
</TableBody>
);
}}
/>
</Table>
</TableContainer>
</Card>
);
}
My Table Row:
export default function FieldRow({ row, selected }: Props) {
const { name } = row;
return (
<TableRow hover selected={selected}>
<TableCell padding="checkbox">
<Checkbox checked={selected} />
</TableCell>
<TableCell sx={{ display: "flex", alignItems: "center" }}>
{name}
</TableCell>
</TableRow>
);
}
Am I incorrect in creating a controller for the component? Should it instead be on the component?
If that's the case then how can I use the names to properly track the components?
I have created an example Sandbox below