I am using React and Typescript to build a carousel of tabs where each tab has a different size. I need to get these tab sizes to correctly calculate how many tabs fit in each view. How can I get the width of each such child node in React?
I was able to retrieve tab nodes using ref:
const tabs = tabsRef.current;
tabs.childNodes.forEach((tab: ChildNode) => {
// I need the width of the tab here
});
I tried using tab.clientWidth, however I got the following error Property 'clientWidth' does not exist on type 'ChildNode'.
I then tried a workaround
tab.firstChild.parentElement.clientWidth;
However, this throws an exception for elements that don't have a child. Is there another way to achieve this?
ChildNode is a mixin and as so it doesn't contain any width properties as some of the nodes might have no width (ie. DocumentType). However, if you know the type(s) of your child nodes, you can use cast to make typescript happy:
(tabs.childNodes as NodeListOf<HTMLDivElement>).forEach((tab: HTMLDivElement) => {
console.log(tab.offsetWidth);
console.log(tab.clientWidth);
})
In case you have multiple element types you can define them all:
const tabsChildren = tabs.childNodes as NodeListOf<HTMLDivElement | HTMLSpanElement | HTMLButtonElement>;
or just use any as the last resort fix:
const tabsChildren = tabs.childNodes as NodeListOf<any>;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With