I’ve created a DMC select dropdown that I think works better, by accepting both labels and values as options:
// Function to convert values back to labels for display
dagfuncs.getDisplayLabel = function (params) {
// If no value, return empty string
if (
params.value === undefined ||
params.value === null ||
params.value === ""
) {
return "";
}
// Get options from cell editor params
const options = params.colDef.cellEditorParams.options;
if (!options || !Array.isArray(options)) {
return params.value;
}
// Find the option with matching value and return its label
const option = options.find((opt) => opt.value === params.value);
return option ? option.label : params.value;
};
dagfuncs.SelectDMC = class {
// gets called once before the renderer is used
init(params) {
// store the params
this.params = params;
// Store the key-value pairs for the options as label: value objects
this.options = {};
params.options.forEach((option) => {
this.options[option.label] = option.value;
});
// Flag to prevent multiple focus cycles
this.isActivating = false;
// Function for when Dash component sends props back to the component / server
const setProps = (props) => {
console.log("Mantine setProps called with:", props);
// if (typeof props.value != typeof undefined) {
if (props.searchValue !== undefined) {
// When searchValue changes (user selects a label), find the corresponding value
const selectedValue = this.options[props.searchValue];
console.log(
`Selected "${props.searchValue}" with value "${selectedValue}"`
);
// Update the value
this.value = selectedValue;
// re-enables keyboard event
delete params.colDef.suppressKeyboardEvent;
// tells the grid to stop editing the cell
params.api.stopEditing();
// Return focus to grid
if (this.prevFocus) {
this.prevFocus.focus();
}
}
};
// create an element for the editor
this.eInput = document.createElement("div");
// create the root for rendering the React component
this.root = ReactDOM.createRoot(this.eInput);
// Get MantineProvider and Select from window
const MantineProvider = window.dash_mantine_components.MantineProvider;
const Select = window.dash_mantine_components.Select;
// Get global theme, styles, and other settings if available
const globalMantineConfig = {
theme: window.dash_mantine_components.mantineTheme || {},
styles: window.dash_mantine_components.mantineStyles || {},
colorScheme: window.dash_mantine_components.mantineColorScheme || "light",
emotionCache: window.dash_mantine_components.mantineEmotionCache || null,
withGlobalStyles: true,
withNormalizeCSS: true,
};
// Find the label that corresponds to the current value
const currentLabel =
Object.keys(this.options).find(
(label) => this.options[label] === params.value
) || "";
console.log(
`Initializing with value: ${params.value}, label: ${currentLabel}`
);
// Render the Select component wrapped in the MantineProvider
this.root.render(
React.createElement(
MantineProvider,
globalMantineConfig,
React.createElement(Select, {
data: params.options,
value: currentLabel, // Use the label, not the value
searchValue: currentLabel,
setProps,
style: {
position: "fixed",
width: params.column.actualWidth - 2,
zIndex: 1000, // Ensure dropdown appears above other elements
...params.style,
},
allowDeselect: params.allowDeselect,
checkIconPosition: params.checkIconPosition,
className: params.className,
classNames: params.classNames,
clearButtonProps: params.clearButtonProps,
// clearable: params.clearable,
clearable: params.clearable !== false,
comboboxProps: params.comboboxProps,
darkHidden: params.darkHidden,
description: params.description,
descriptionProps: params.descriptionProps,
disabled: params.disabled,
dropdownOpened: params.dropdownOpened,
error: params.error,
errorProps: params.errorProps,
hiddenFrom: params.hiddenFrom,
hiddenInputProps: params.hiddenInputProps,
inputWrapperOrder: params.inputWrapperOrder,
label: params.label,
labelProps: params.labelProps,
leftSection: params.leftSection,
leftSectionPointerEvents: params.leftSectionPointerEvents,
leftSectionProps: params.leftSectionProps,
leftSectionWidth: params.leftSectionWidth,
lightHidden: params.lightHidden,
limit: params.limit,
loading_state: params.loading_state,
maxDropdownHeight: params.maxDropdownHeight || 280,
mod: params.mod,
name: params.name,
nothingFoundMessage: params.nothingFoundMessage,
persisted_props: params.persisted_props,
persistence: params.persistence,
persistence_type: params.persistence_type,
placeholder: params.placeholder || "Select...",
pointer: params.pointer,
radius: params.radius,
readOnly: params.readOnly,
required: params.required,
rightSection: params.rightSection,
rightSectionPointerEvents: params.rightSectionPointerEvents,
rightSectionProps: params.rightSectionProps,
rightSectionWidth: params.rightSectionWidth,
scrollAreaProps: params.scrollAreaProps,
searchValue: params.searchValue,
searchable: params.searchable,
selectFirstOptionOnChange: params.selectFirstOptionOnChange,
size: params.size,
styles: params.styles,
tabIndex: params.tabIndex,
variant: params.variant,
visibleFrom: params.visibleFrom,
withAsterisk: params.withAsterisk,
withCheckIcon: params.withCheckIcon,
withErrorStyles: params.withErrorStyles,
withScrollArea: params.withScrollArea,
wrapperProps: params.wrapperProps,
})
)
);
// allow focus event
this.eInput.tabIndex = "0";
// set editor value to the value from the cell
this.value = params.value;
}
// gets called once when grid is ready to insert the element
getGui() {
return this.eInput;
}
focusChild() {
console.log("focusChild called");
// Prevent multiple activations
if (this.isActivating) return;
this.isActivating = true;
// Use a sequence of timed actions to ensure proper dropdown behavior
setTimeout(() => {
if (!this.eInput) {
console.log("eInput not available");
this.isActivating = false;
return;
}
// Find the input element
const input = this.eInput.querySelector(".mantine-Select-input");
if (!input) {
console.log("Mantine input not found");
this.isActivating = false;
return;
}
// Make the input focusable
input.tabIndex = "1";
// Disable keyboard events in the grid while editing
this.params.colDef.suppressKeyboardEvent = (params) => {
return params.editing;
};
// Focus the input
input.focus();
console.log("Input focused");
// Click the input to open the dropdown after a delay
setTimeout(() => {
input.click();
console.log("Input clicked to open dropdown");
// Reset activation flag after dropdown should be fully visible
setTimeout(() => {
this.isActivating = false;
console.log("Dropdown should now be visible");
}, 100);
}, 150);
}, 100);
}
// focus and select can be done after the GUI is attached
afterGuiAttached() {
console.log("afterGuiAttached called");
// Store the currently active element for later focus restoration
this.prevFocus = document.activeElement;
// PROPERLY REGISTER the event handler - this is critical!
this.eInput.addEventListener("focus", this.focusChild);
// trigger focus event
this.eInput.focus();
// Also call the handler directly to ensure dropdown opens
// without relying solely on the focus event
this.focusChild();
}
// returns the new value after editing
getValue() {
console.log(`Returning value: ${this.value}`);
return this.value;
}
// safely unmount the React component
destroy() {
console.log("destroy called");
// Remove event listener to prevent memory leaks
this.eInput.removeEventListener("focus", this.focusChild);
// Delay the unmounting to avoid race conditions during render
setTimeout(() => {
if (this.root) {
// unmount the component and clean up
this.root.unmount();
this.root = null; // clear reference to avoid further operations
}
// set focus back to the grid's previously active cell
if (this.prevFocus) {
this.prevFocus.focus();
}
}, 0); // ensure unmount happens after rendering is complete
}
};
here are the column definitions in Python:
columnDefs = [
{
"field": "city",
"cellEditor": {"function": "SelectDMC"},
"cellEditorParams": {
"options": [
{"label": "New York City", "value": "NYC"},
{"label": "Seattle", "value": "SEA"},
{"label": "San Francisco", "value": "SFO", "disabled": True},
],
"placeholder": "Select a City",
"maxDropdownHeight": 280,
"searchable": True,
"clearable": True,
},
"valueFormatter": {"function": "getDisplayLabel(params)"},
"cellEditorPopup": True,
"singleClickEdit": True,
},
]