How to get the table column width after render in react?

Viewed 510

I am trying to make sticky header in table in react and in order to do this, copied the table head and make the container position absolute relative to the table div. But the issue is the width of the table cell is not the same. I want to get the width of each column in the table and set the sticky header column width to make them the same. How can I do it after render?

This is the code structure:

<div className="tableDataContainer">
    <div className="stickyHeader">
        <Table>
            <TableHead></TableHead>
        </Table>
    </div>
    <Table>
        <TableHead></TableHead>
        <TableBody></TableBody>
    </Table>
</div>
2 Answers

Might be a bit overkill but you could use a ref on your cell and get its width using the clientWidth property or getBoundingClientRect method.

"Refs provide a way to access DOM nodes or React elements created in the render method." - React ref doc

You can create a ref using either the createRef method (if your component is a class component) or the useRef hook (if your component is a functional component).

You can get width of one object in React after render by using ref prop and useRef hook. Something like:

const refElem = React.useRef(0);
...
<button ref={refElem}>This is a button 1</button> //<-- I'm using a button just to make an example

Then to access to width just call refElem.style.width.

Related