'React: Get DOM data from sibling elements
(I am new to React and TypeScript so apologies ahead of time)
I am trying to build a bar that I can fill between 2 elements and I think the best way might be to figure out where those two elements are after the component is built and then do some logic in order to size the bar properly.
For reference here is what im trying to build:

How / is it possible to get the DOM using something like getBoundingClientRect() in order to know how big and where the bar should start and stop?
Here is the component set up so far:
import React from "react";
import './CardLineItem.css';
import CardLineItemImage from "./CardLineItemImage";
import { FaChevronRight } from 'react-icons/fa';
import CardLineItemProgressBar from "./CardLineItemProgressBar";
export default class CardLineItem extends React.Component {
render() {
return (
<div className="CardLineItem">
<CardLineItemImage cardUrl="platinum-card.png" altText="platinum-card"/>
<FaChevronRight className="CardLineItemChevron" size="25%"/>
<CardLineItemProgressBar />
</div>
)
}
}
I looked into componentDidMount and this.children.toArray but that never returns anything. Suggestions on how I could best do this? CardLineItemProgressBar is the element I need to be flexible depending on the browser size.
Thanks!
Solution 1:[1]
Rather than reading the size and position of the other items, and making adjustments before the DOM paints, it's much better for performance to rely on CSS to do something like this.
I would highly recommend seeing if flex or grid can fulfill what you're trying to do here.
By bringing the progress bar component between the two other components in the JSX tree like this ...
<div className="CardLineItem">
<CardLineItemImage cardUrl="platinum-card.png" altText="platinum-card"/>
<CardLineItemProgressBar className="CardLineItemProgress" />
<FaChevronRight className="CardLineItemChevron" size="25%"/>
</div>
... you can add the flex style to the .CardLineItem and a .CardLineItemProgress class to have your progress bar grow accordingly to fill the space.
.CardLineItem {
// ... your other styles
display: flex;
gap: 10px;
}
.CardLineItemProgress {
flex-grow: 1;
align-self: flex-end;
}
That said, if you really would prefer to add JS calculations to manually calculate and set the size, getSnapshotBeforeUpdate() should be what you're looking for.
And if you ever switch to React functional components with hooks (standardized after React 16.8), then the hook you'd be looking for is useLayoutEffect()
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 | Jacob K |
