Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

224
Views
how to calculate width of component in react js?

I am trying to calculate the width of child component .is it possible to calculate width of children's ? here is my code here is my code https://codesandbox.io/s/reverent-hermann-yt7es?file=/src/App.js

<Tabs>
      {data.map((i) => (
        <li>{i}</li>
      ))}
    </Tabs>

TABS.js

import React, { useEffect, useRef } from "react";

const Tabs = ({ children }) => {
  const tabsRef = useRef(null);

  const setTabsDimensions = () => {
    if (!tabsRef.current) {
      return;
    }

    // initial wrapper width calculation
    const blockWidth = tabsRef.current.offsetWidth;
    // const showMoreWidth = moreItemRef.current.offsetWidth;

    // calculate width and offset for each tab
    let tabsTotalWidth = 0;
    const tabDimensions = {};

    children.forEach((tab, index) => {
      if (tab) {
        console.log(tab);
        
        // const width = !isMobile ? 200 : 110;

        // tabDimensions[index] = {
        //   width,
        //   offset: tabsTotalWidth
        // };
        // tabsTotalWidth += width;
      }
    });
  };

  useEffect(() => {
    setTabsDimensions();
  });
  return (
    <ul ref={tabsRef} className="rc64nav">
      {children}
    </ul>
  );
};

export default Tabs;

I know using ref we can access the dom property but how to apply ref in children element element. here i am trying to calculate all item width

   children.forEach((tab, index) => {
              if (tab) {
                console.log(tab);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Just answer your question how to get child's ref.

  const Parent = () => {
    const childRef = useRef()

    // An example of use the childRef
    const onClick = () => {
     if (!childRef.current) return
      
     console.log(childRef.current.offsetWidth)
    }


    return <Child childRef={childRef} />
  }

  const Child = ({ childRef }) => {
   return <div ref={childRef}>Hello Child</div>
  }

NOTE: the way I pass ref here is exactly the same way you pass parent method to child. And also ref supports two formats, i'm using the simple one, but you can also use () => {} format. https://reactjs.org/docs/refs-and-the-dom.html

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!