Search code examples
javascriptreactjsreact-routermenuantd

Change Menu Color for Selected Button (Using Ant Design with React)


Hello i'am writing to inquire about the process for changing the menu associated with a selected button. I am currently using Ant Design (antd) with React and would like to update the options displayed when the button is clicked.

Could you please provide guidance on how to modify the menu content for the selected button within the Ant Design framework? Any instructions or assistance you can offer would be greatly appreciated.

Thank you for your attention to this matter. I look forward to your response.

Sincerely

React code:

import BreadcumbCustom from 'views/share/BreadcumbCustom.jsx'
import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { AppstoreOutlined, MailOutlined } from '@ant-design/icons'
import { Menu } from 'antd'

const items = [
  {
    label: 'Tracciati',
    key: '1-1',
    icon: <MailOutlined />,
  },
  {
    label: 'Classificazioni',
    key: '1-2',
    icon: <AppstoreOutlined />,
  },
]
export default function MenuConfigurazioni() {
  const navigate = useNavigate()
  const [current, setCurrent] = useState()
  const handleDropdownItemClick = (e) => {
    setCurrent(e.key)
    if (e.key === '1-1') {
      navigate('/admin/configurazione')
    } else {
      navigate('/admin/configurazione/classificazioni')
    }
  }

  return (
    <div>
      <BreadcumbCustom title={'Configurazione'} />
      <Menu
        onClick={handleDropdownItemClick}
        selectedKeys={[current]}
        mode='horizontal'
        items={items}
      />
    </div>
  )
}

Solution

  • There are two ways to achieve this

    1. You can use CSS like this, demo

        .custom-menu .ant-menu-item-selected,
        .custom-menu .ant-menu-submenu-selected,
        .ant-menu-item-selected {
          color: "red !important";
        }

    1. Otherwise you can use the ConfigProvider and itemSelectedColor demo

    <ConfigProvider
      theme={{
        components: {
          Menu: { itemSelectedColor: '#c22525 !important' },
        },
      }}
    >
      <Space>
        <Menu
          className="custom-menu"
          onClick={onClick}
          selectedKeys={[current]}
          mode="horizontal"
          items={items}
        />
      </Space>
    </ConfigProvider>

    enter image description here Other menu design tokens