Search code examples
javascriptag-gridag-grid-reactag-grid-validation

In Ag-grid-react how to disable update button if edited cell is not valid?


I'm trying to disable update button after validating cell editor enter image description here

link for full code, https://stackblitz.com/edit/react-hooks-complex-editor-3b7ybk?file=src%2FApp.js,src%2FComponents%2FEditors%2FSimpleEditor.jsx,src%2FComponents%2FEditors%2FAsyncValidationEditor.jsx,src%2Folympic_lists.js,src%2Fcolumns.js,src%2Futils.js,src%2FApp.css


Solution

  • In the renderer - ActionsRenderer

    • expose a method for updating the button state.
      • To do this, use forwardRef and useImperativeHandle
    • and I added a separate state updateDisabled so other buttons are not affected by the state change ie "cancel"

    Below are the changes I made.

    export default forwardRef((props, ref) => {
    ...
      let [updateDisabled, setUpdateDisabled] = useState(false);
    ...
      useImperativeHandle(ref, () => ({
        exposedUpdateDisabled: setUpdateDisabled,
      }));
    })
    

    In the validator - AsyncValidationEditor(or whatever editor you plan to use)

    • get the instance of the actions renderer and update the renderer in your validator logic.

        export default forwardRef((props, ref) => {
        ...
          useEffect(() => {
        ...
            new Promise(...)
              .then((valid) => {
                setValid(valid);
                setValidating(false);
      
                // get actions renderer for this row
                const actionInstance = 
                  props.api.getCellRendererInstances({
                  rowNodes: [props.node],
                  columns: ['actions'],
                })[0].componentInstance;
      
                // use exposed api to update state on the renderer
                actionInstance.exposedUpdateDisabled(!valid);
        ...
         }, [debouncedInputVal]);
      

      })

    here is your updated code : https://stackblitz.com/edit/react-hooks-complex-editor-5xr8na?file=src%2FApp.js,src%2FComponents%2FEditors%2FSimpleEditor.jsx,src%2FComponents%2FEditors%2FAsyncValidationEditor.jsx,src%2Folympic_lists.js,src%2Fcolumns.js,src%2Futils.js,src%2FComponents%2FRenderers%2FActionsRenderer.jsx