ag-Grid provides a number of out of the box editors that will fulfill most simple use cases. However, In the case that you would like to extend the behaviour of an editor, ag-Grid allows you to create your own Custom Editors:
The SimpleEditor component is applied to the Athlete column.
This SimpleEditor component shows the bare bones configuration needed for a custom editor written using React Hooks.
// src/Components/Editors/SimpleEditor.jsx
export default forwardRef((props, ref) => {
const inputRef = useRef();
const [value, setValue] = useState('');
function inputHandler(e) {
setValue(e.target.value);
}
useImperativeHandle(ref, () => {
return {
getValue: () => {
return value;
},
afterGuiAttached: () => {
setValue(props.value);
inputRef.current.focus();
inputRef.current.select();
}
};
});
return (
<input
type="text"
className="ag-input-field-input ag-text-field-input"
ref={inputRef}
onChange={inputHandler}
value={value}
placeholder={'Enter ' + props.column.colId}
/>
)
})
The result of editing is returned to ag-Grid in the getValue
(required) lifecycle method. We’ve also included the afterGuiAttached
(optional)hook where we focus on and highlight the component after it has mounted.
It’s important to note that when using React Hooks that all custom editors should be wrapped in React.forwardRef
and all ag-Grid lifecycle methods should be returned in React.useImperativeHandle
.
Learn more about ag-Grid Custom Editors
Learn more about using React Hooks with ag-Grid
The AsyncValidation component is applied to the Sports column.
This component demonstrates how asynchronous validation can be configured inside a custom editor.
We’ve mocked a server call using a Promise that gets resolved after a user has finished typing and updates the component’s valid
state variable:
// src/Components/Editors/AsyncValidationEditor.jsx
export default forwardRef((props, ref) => {
// [...]
const debouncedInputVal = useDebounce(inputValue, 1000);
function inputHandler(e) {
setTouched(true);
setInputValue(e.target.value);
setValidating(true);
}
useEffect(() => {
// random time between 0 and 1000ms
let timeout = Math.floor(Math.random() * 1000);
new Promise((resolve, reject) => {
if (inputValue === '') {
resolve(false);
} else {
setTimeout(() => {
resolve(props.condition(inputValue));
}, timeout);
}
})
.then(valid => {
setValid(valid);
setValidating(false)
})
.catch(err => console.log(err));
}, [debouncedInputVal]);
// [...]
})
The valid
state variable then dictates whether or not the editor’s updated value will be returned to the grid in the isCancelAfterEnd
(optional) lifecycle hook:
// src/Components/Editors/AsyncValidationEditor.jsx
useImperativeHandle(ref, () => {
return {
// [...]
isCancelAfterEnd: () => {
return !valid || validating;
},
};
});
Learn more about Editing Cells.
#ag-grid #react #javascript #web-development #programming #react hooks