import React, { ChangeEventHandler, useCallback, useEffect, useRef, useState, } from "react"; import { Box, Input, SxProps, TableCell } from "@mui/material"; interface Props { value: T; onChange: (newValue?: T) => void; renderValue?: (value: T) => string; convertValue: (inputValue?: string) => T; cellSx?: SxProps; inputSx?: SxProps; } const TableCellEdit = ({ value, renderValue = (val) => `${val}`, convertValue, onChange, cellSx, inputSx, }: Props) => { const [editMode, setEditMode] = useState(false); const [input, setInput] = useState(); const inputRef = useRef(null); const onClick = useCallback(() => { setEditMode(true); setInput(`${value}`); }, [value]); const onInputChange = useCallback>( (e) => setInput(e.target.value), [], ); const onBlur = useCallback(() => { setEditMode(false); onChange(convertValue(input)); setInput(undefined); }, [convertValue, input, onChange]); useEffect(() => { if (editMode && inputRef.current) { inputRef.current?.focus(); } }, [editMode]); return ( {renderValue(value)} ); }; export default TableCellEdit;