getboundingclientrect in react refs

Solutions on MaxInterview for getboundingclientrect in react refs by the best coders in the world

showing results for - "getboundingclientrect in react refs"
Federica
20 Jun 2016
1class TooltipContainer extends React.Component {
2  constructor(props) {
3    super(props);
4
5    const defaultRect = { left: 0, width: 0 };
6
7    this.state = {
8      containerRect: defaultRect,
9      tooltipRect: defaultRect
10    };
11
12    this.containerRef = React.createRef();
13    this.tooltipRef = React.createRef();
14    this.getRectsInterval = undefined;
15  }
16
17  componentDidMount() {
18    this.getRectsInterval = setInterval(() => {
19      this.setState(state => {
20        const containerRect = this.containerRef.current.getBoundingClientRect();
21        return JSON.stringify(containerRect) !== JSON.stringify(state.containerRect) ? null : { containerRect };
22      });
23      this.setState(state => {
24        const tooltipRect = this.tooltipRef.current.getBoundingClientRect();
25        return JSON.stringify(tooltipRect) === JSON.stringify(state.tooltipRect) ? null : { tooltipRect };
26      });
27    }, 10);
28  }
29
30  componentWillUnmount() {
31    clearInterval(this.getRectsInterval);
32  }
33
34  render() {
35    const left = this.state.containerRect.left +
36      this.state.containerRect.width / 2 -
37      this.state.tooltipRect.width / 2 +
38      "px";
39    
40    return (
41      <div
42        ref={this.containerRef}
43        style={{ display: "inline-block", position: "relative" }}
44      >
45        <span>Here is some text that will make the parent expand</span>
46        <img src="https://www.telegraph.co.uk/content/dam/pets/2017/01/06/1-JS117202740-yana-two-face-cat-news_trans_NvBQzQNjv4BqJNqHJA5DVIMqgv_1zKR2kxRY9bnFVTp4QZlQjJfe6H0.jpg?imwidth=450" />
47        <div
48          ref={this.tooltipRef}
49          style={{
50            background: "blue",
51            position: "absolute",
52            top: 0,
53            left
54          }}
55        >
56          Tooltip
57        </div>
58      </div>
59    );
60  }
61}
62