Articles in this section
Category / Section

Maintaining the Selected State of Menu Items with Syncfusion MenuComponent in React

4 mins read

This article will guide you through the process of ensuring that the “e-selected” class persists on the selected menu item. When interacting with a menu component, it’s common to highlight the selected item by applying a specific CSS class. In the case of the Syncfusion MenuComponent, the “e-custom-selected” class is used for this purpose.
However, maintaining this class when the user clicks elsewhere on the page can be a challenge.

Applying a custom class to the selected Item

To add and maintain the “e-custom-selected” class or apply a custom class to the selected item, you can use the select and beforeOpen events of the MenuComponent.

Here’s how you can implement this in your React component:

let selectedItem; // To maintain the selected item.
// Define your menu items
const menuItems = [
    // ... (menu items definition)
];

// Event handler for the select event
function onSelect(args) {
    this.selectedItem = args.item.text;
    if (args.item.parentObj.parentObj) {
       let liList = this.element.querySelectorAll('li');
       for (let i = 0; i < liList.length; i++) {
           liList[i].classList.remove("e-custom-selected");
       }
    } else {
       // Add the "e-custom-selected" class to the main menu item
       args.element.classList.add("e-custom-selected");
    }
}

// Event handler to apply the custom class to the sub menu item
function onOpen(args) {
    let liList = args.element.querySelectorAll('li');
    for (let i = 0; i < liList.length; i++) {
        if (args.items[i].text === this.selectedItem) {
           liList[i].classList.add("e-custom-selected");
        }
    }
}

// Menu component definition
function Default() {
    React.useEffect(() => {
        // ... (any additional setup)
    }, []);

    return (
        <div className='control-pane'>
            <div className='control-section'>
                <div className='menu-section'>
                    <div className='menu-control'>
                        <MenuComponent items={menuItems} select={onSelect} beforeOpen={onOpen}></MenuComponent>
                    </div>
                </div>
            </div>
        </div>
    );
}

During the select event, we modify the selectedItem property. If the selected item is part of the main menu, we proceed to include the class in the main menu item. Additionally, in the beforeClose event, we append e-custom-selected to the selected menu item.

Demo

Refer to the working sample for additional details and implementation: Menu Sample

References

By following the steps outlined above, you can maintain the selected state of menu items in your React application using the Syncfusion MenuComponent.

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied