'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 1:[1]

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>)
          
    };

Solution 2:[2]

If you really don't want to use css/less, you can just use inline styles:

let style = {};

if (condition) style.color = 'red';

return <Component style={style} />

But you can also do it (a little more cleanly in my opinion) by adding a class based on a condition in JavaScript and handle the styling in css/less:

let class;

if (condition) class = 'specialClass';

return <Component className={class} />

Solution 3:[3]

You can also try some css variable to update active color from the js code.

const element = document.documentElement;
if (element) {
    element.style.setProperty('--active_tab_color', 'red'); // Use Dynamic color variable here.
}

and then go to your css file and use that variable there.

.ant-tabs .ant-tabs-nav-list .ant-tabs-ink-bar  {
    background-color: var(--active_tab_color);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 larz
Solution 3 SuNdAr RaJa