How to Create Custom Application Menus in Electron: A Complete Guide
Use Menu.buildFromTemplate() to construct a menu from a declarative array of options, then attach it to your application with Menu.setApplicationMenu() to enable native OS menu integration.
Electron's native menu system is built on two core classes—Menu and MenuItem—implemented in the browser-side API. These classes, defined in lib/browser/api/menu.ts and lib/browser/api/menu-item.ts, provide the foundation for creating custom application menus in Electron that integrate seamlessly with macOS, Windows, and Linux native UI conventions.
Core Architecture of Electron's Menu System
The menu architecture centers on two primary components:
-
Menu: Represents a native menu container. Defined in
lib/browser/api/menu.ts, this class provides instance methods likeappend(),insert(),popup(), andclosePopup(), along with static helpers includingbuildFromTemplate(),setApplicationMenu(), andgetApplicationMenu(). -
MenuItem: Represents individual entries within a menu. Implemented in
lib/browser/api/menu-item.ts, each item encapsulates properties such aslabel,type(normal,separator,submenu,checkbox,radio),accelerator, andclickhandlers.
When constructing menus, Electron maintains internal mappings through commandsMap (linking command IDs to items) and groupsMap (managing radio button groups), ensuring proper state management for interactive elements.
Creating Custom Application Menus
Electron offers two primary approaches for building menus: template-based construction (recommended) and programmatic assembly.
Template-Based Construction (Recommended)
The Menu.buildFromTemplate() method, defined in lib/browser/api/menu.ts (lines 9-30), provides a declarative approach. This static method validates the template (areValidTemplateItems), sorts items (sortTemplate), removes redundant separators (removeExtraSeparators), and instantiates MenuItem objects.
const { app, Menu } = require('electron/main');
app.whenReady().then(() => {
const template = [
{
label: 'File',
submenu: [
{ role: 'quit' }
]
},
{
label: 'View',
submenu: [
{ role: 'reload' },
{ role: 'toggledevtools' },
{ type: 'separator' },
{ role: 'resetzoom' },
{ role: 'zoomin' },
{ role: 'zoomout' }
]
}
];
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
});
Programmatic Construction
For dynamic menu generation, instantiate Menu and MenuItem directly using the constructors defined in lib/browser/api/menu.ts and lib/browser/api/menu-item.ts:
const { app, Menu, MenuItem } = require('electron/main');
app.whenReady().then(() => {
const submenu = new Menu();
submenu.append(new MenuItem({ label: 'Hello' }));
submenu.append(new MenuItem({ type: 'separator' }));
submenu.append(new MenuItem({
label: 'Electron',
type: 'checkbox',
checked: true
}));
const menu = new Menu();
menu.append(new MenuItem({ label: 'Menu', submenu }));
Menu.setApplicationMenu(menu);
});
This approach calls Menu.prototype.append (lines 42-45 in menu.ts), which delegates to insertItemByType for proper placement and radio group management.
Advanced Customization Techniques
Leveraging Built-in Roles
Electron's role system, defined in lib/browser/api/menu-item-roles.ts, provides platform-native behaviors without manual implementation. Roles automatically assign appropriate labels, accelerators, and actions:
{
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' }
]
}
When a role is specified, MenuItem normalizes it (toLowerCase) and retrieves default properties via roles.getDefaultSubmenu and roles.getDefaultType. The role's execute function runs before any user-supplied click handler.
Platform-Specific Features (macOS)
macOS supports additional MenuItem properties including icon, sublabel, and toolTip. These are handled in Menu.prototype.insert (lines 60-64 of menu.ts):
const { nativeImage } = require('electron/common');
const icon = nativeImage.createFromPath('assets/icon.png');
const menu = Menu.buildFromTemplate([
{
label: 'Tools',
submenu: [
{
label: 'Green Circle',
icon: icon,
sublabel: 'Demo icon',
click: () => console.log('Clicked')
}
]
}
]);
Note that icon and sublabel require macOS 14+ and have no effect on Windows or Linux.
Programmatic Item Positioning
Control menu item order using positioning properties processed by insertItemByType in menu.ts:
Menu.buildFromTemplate([
{ id: 'first', label: 'First' },
{ id: 'second', label: 'Second', after: ['first'] },
{ id: 'third', label: 'Third', before: ['second'] }
]);
Valid positioning keywords include before, after, beforeGroupContaining, and afterGroupContaining. These are resolved during the construction phase to determine final item placement.
Platform Differences
Electron's menu implementation adapts to platform conventions through conditional logic in Menu.setApplicationMenu:
- macOS: The menu becomes a global application menu bar via
bindings.setApplicationMenu. EachBaseWindowinherits this menu automatically. - Windows/Linux: The menu attaches to individual windows through
window.setMenu(). The menu bar appears at the top of each window frame.
Radio groups and checkbox states are managed consistently across platforms through the groupsMap and commandsMap internal structures defined in menu.ts.
Summary
- Menu and MenuItem classes in
lib/browser/api/menu.tsandlib/browser/api/menu-item.tsform the foundation of Electron's native menu system. - Use Menu.buildFromTemplate() for declarative menu construction; it handles validation, sorting, and separator cleanup automatically via utilities in
lib/browser/api/menu-utils.ts. - Apply Menu.setApplicationMenu() to attach menus globally on macOS or per-window on Windows/Linux.
- Leverage roles defined in
lib/browser/api/menu-item-roles.tsfor platform-native behaviors without custom click handlers. - Control item positioning with
before,after, and group keywords during template construction. - Access macOS-specific features like icons and sublabels through additional
MenuItemproperties.
Frequently Asked Questions
What is the difference between Menu.buildFromTemplate and creating MenuItems manually?
Menu.buildFromTemplate() provides a declarative API that automatically validates items via areValidTemplateItems, sorts them according to positioning keywords, removes redundant separators through removeExtraSeparators, and instantiates MenuItem objects. Manual construction using new MenuItem() and menu.append() offers more dynamic control but requires you to handle sorting and validation yourself. Both approaches ultimately use the same underlying classes defined in lib/browser/api/menu.ts and lib/browser/api/menu-item.ts.
How do radio groups work in Electron menus?
Radio groups are managed internally through the groupsMap in the Menu class. When you create a MenuItem with type: 'radio', Electron generates a group ID via generateGroupId and ensures only one item in that group remains checked at a time. This logic is handled in insertItemByType within lib/browser/api/menu.ts, maintaining consistent behavior across macOS, Windows, and Linux.
Can I update the application menu after the app has started?
Yes. You can call Menu.setApplicationMenu() at any time to replace the current menu. On macOS, this updates the global menu bar immediately via the native bindings.setApplicationMenu. On Windows and Linux, the new menu applies to all current and future windows. To modify specific items without rebuilding the entire menu, you can reference items by ID and update their properties, though rebuilding via buildFromTemplate is the most common pattern for substantial changes.
Why do some MenuItem properties only work on macOS?
Certain properties like icon, sublabel, and toolTip rely on AppKit-specific features available only in macOS menus. These properties are processed in Menu.prototype.insert (lines 60-64 of lib/browser/api/menu.ts) but have no effect on Windows or Linux, where the underlying native menu APIs do not support these attributes. For cross-platform compatibility, use these properties only when process.platform === 'darwin'.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →