Search code examples
reactjstabsantd

AntD custom color for active tab without css/less,


I am trying to change the background color for the active tab from AntD tabs, I can achieve that with less file by targeting:

.ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn {
  color: blue;
}

so that is not a problem, my problem is that I need to change the background color of the active tab based on javascript condition and I am not sure how to target the active tab with javascript and without css/less.

Any ideas how can I achieve that?


Solution

  • You can get the element, using the querySelector function(https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector).

     const Demo = () => {
        function callback(key) {
        updateTabBackground();
      }
    
      useEffect(()=> {
       updateTabBackground();
      }, []);
    
      const updateTabBackground = () => {
        const tab = document.querySelector('[role="tab"][aria-selected="true"]');
        console.log(tab)
    
        if(tab) {
          tab.style.background = 'red';
        }
      }
            
      return (
          <Tabs defaultActiveKey="1" onChange={callback}>
              <TabPane tab="Tab 1" key="1">
                Content of Tab Pane 1
              </TabPane>
              <TabPane tab="Tab 2" key="2">
                Content of Tab Pane 2
              </TabPane>
              <TabPane tab="Tab 3" key="3">
                Content of Tab Pane 3
              </TabPane>
          </Tabs>)
              
        };