Search code examples
javascriptreactjsmaterial-uimaterial-table

How to use custom 'editComponent' in material-table?


I'm trying to use 'material-table' in my project. My 'icon' column contains icon name. I need change this icon by selecting it from external dialog. I have problem with updating table data from external dialog. When I use 'input' element and I change icon name, it works correctly.

editComponent: props => (
  <input
    type="text"
    value={props.value}
    onChange={e => props.onChange(e.target.value)}
  />
)

I don't know, how to achive this result with my dialog. I've created the following snipped project to show in details what I need: https://codesandbox.io/embed/gifted-liskov-ih72m

When I change icon name by text and save changes - is OK. Changes are saved. When I change icon by selecting it from external dialog and save changes - it doesn't work.

editComponent: props => (
  <SelectIconDialog
    value={props.value}
    onChange={e => props.onChange(e.target.value)}
  />
)

I don't know, how to invoke 'onChange' given by props inside the 'SelectIconDilog'.

export default function SelectIconDialog(props) {
    const { value, onChange } = props;
    const [open, setOpen] = React.useState(false);
    const [selectedValue, setSelectedValue] = React.useState(value);

    function handleClickOpen() {
        setOpen(true);
    }

    const handleClose = value => {
        setOpen(false);
        setSelectedValue(value);
        //onChange(value); // it doesn't work
    };

    return (
        <div>
            <Tooltip title={selectedValue}>
                <IconButton
                    onClick={handleClickOpen}
                    color="default"
                >
                    <DynamicIcon 
                        iconName={selectedValue} 
                        // onChange={onChange} // it doesn't work
                    />
                </IconButton>
            </Tooltip>
            <SimpleDialog selectedValue={selectedValue} open={open} onClose={handleClose} />
        </div>
    );
}

Solution

  • In SelectIconDialog use onChange={e => props.onChange(e)}, because e is the icon name and you want to assign it to your input.

      const [state, setState] = React.useState({
        columns: [
          {
           ...
            editComponent: props => (
              <SelectIconDialog value={props.value} onChange={props.onChange} />
            )
          },
          ...
    }
    

    Moreover, in SimpleDialog you getting an error because you didn't assign unique keys to your iconNames, try:

      <div>
        {iconsNames.map((iName, key) => (
          <Tooltip title={iName} key={key}>
            <IconButton onClick={() => handleItemClick(iName)}>
              <DynamicIcon iconName={iName} />
            </IconButton>
          </Tooltip>
        ))}
      </div>;
    

    Demo:

    Edit stupefied-voice-bf5hg