3

I have created a tab component, the one part which I am not able to achieve is that, instead of TabIndicator to entirely take the length of the tab container I need to set only the text width.

Since each text has different width I am using js to calculate it, but instead of getting the width, I am able to get the container width.

How can I make the active TabIndicator line only expand from the start of the text to the end of text.

I am able to achieve the container width. Adding the sandbox link for the same.

Sandbox

dev
  • 814
  • 10
  • 27

1 Answers1

1

It's simple. You need to subtract extra paddings while calculating the start and width of the indicator.
.tab has 6px padding horizontally
.tab-default-container has 1rem padding on desktop it's 16px
. So change code something like:

if (tabMeta && tabsMeta) {
 startValue = tabMeta.left - tabsMeta.left + tabsMeta.scrollLeft + 22; //16+6=22
}

//22 from both sides = 44px tor remove.
const newIndicatorStyle = {
   left: startValue,
   width: tabMeta ? tabMeta.width - 44 : 0
};

Updated sandbox.
Note: You've used relative unit rem it may evaluate different on different settings and devices, it may not be 1rem=16px.

The rem (for “root em”) is the font size of the root element of the document.

So do the calculations considering this.

the Hutt
  • 16,980
  • 2
  • 14
  • 44
  • Thanks, just one doubt, if i need to calculate it dynamically how should I do it ? – dev Nov 30 '21 at 06:58
  • I think this should do it: https://stackoverflow.com/a/42769683/15273968 – the Hutt Nov 30 '21 at 07:01
  • No i was referring to the extra paddings part, as of now we are subtracting - 44, how can I get this with js in the sandbox which I have tried, I am able to get the container width not the exact text width – dev Nov 30 '21 at 07:08
  • 1
    for me these changes worked startValue = tabMeta.left - tabsMeta.left + tabsMeta.scrollLeft + 16; , width: tabMeta ? tabMeta.width - 32 : 0, – dev Nov 30 '21 at 08:31
  • `window.getComputedStyle(tab.children[0]).paddingLeft` gives `16px` string. You can use it after parsing it to float/integer. – the Hutt Nov 30 '21 at 08:34
  • My browser is hanging on the sandbox. React is recursively updating dom.. – the Hutt Nov 30 '21 at 08:35
  • On which case, when using window.getComputedStyle or just subtracting 32 and adding 16 ? – dev Nov 30 '21 at 08:40
  • While adding use it as it is and while subtracting multiply it with 2. – the Hutt Nov 30 '21 at 08:49
  • https://codesandbox.io/s/cocky-glitter-2leic, i am not able to see the browser getting hang on this changes startValue = tabMeta.left - tabsMeta.left + tabsMeta.scrollLeft + 16; width: tabMeta ? tabMeta.width - 32 : 0, – dev Nov 30 '21 at 08:55