Search code examples
reactjsag-grid-react

How to trigger a cell change from within a component to update the grid data? (AG Grid - React)


I have a dropdown component within an Ag Grid. But when I change the value, the client-side data object doesn't change.

I'm triggering a function within the component when the dropdown is changed - but how can I tell the "parent" AG Grid to update it's data for that cell? (AG Grid automatically updates it's data when you're just changing text directly in a cell, not using a custom component.)

It seems to have something to do with using getValue(), but I can't seem to find the proper call in the documentation.


Solution

  • Are you using a Cell Renderer or Cell Editor to build the dropdown component?

    If using a Custom Cell Editor, you must implement the getValue method otherwise the grid will not insert the new value into the row after editing is done.

    See this implemented here:

    const CustomCellEditor = forwardRef((props, ref) => {
      const [selectedValue, setSelectedValue] = useState('United States');
      const values = ['United States', 'Russia', 'Canada'];
    
      /* Component Editor Lifecycle methods */
      useImperativeHandle(ref, () => {
        return {
          getValue() {
            return selectedValue;
          },
        };
      });
    
      const onChangeHandler = (event) => {
        setSelectedValue(event.target.value);
      };
      return (
        <div>
          <select value={selectedValue} onChange={onChangeHandler}>
            {values.map((item) => (
              <option>{item}</option>
            ))}
          </select>
        </div>
      );
    });
    

    Plunkr example

    Documentation on Custom Cell Editors