-1

There is ceiling tabBar which represent different part of my page and i try to get each part‘s offsetTop in componentDidMount, then i can switch the tabBar by comparing the document.element.scrollTop to the offsetTop. However i found that i can't get the correct offsetTop of each part in componengtDidMount,since elements didn't being fully rendered.

here are some relative code

const tabList = [
  {
    title: 'xxxx1',
    id: 'feature',
    offsetTop: 0
  },
  {
    title: 'xxxx2',
    id: 'compensation',
    offsetTop: 0
  },
  {
    title: 'xxxx3',
    id: 'faq',
    offsetTop: 0
  },
  {
    title: 'xxxx4',
    id: 'form',
    offsetTop: 0
  }
]

 componentDidMount() {
    this.getEleOffsetTop()
  }

  getEleOffsetTop = () => {
    tabList.forEach(item => {
      let node = document.getElementById(`${item.id}`)
      if (node) {
        item.offsetTop = node.offsetTop
      }
    })
    console.log('tabList', tabList)
  }
Sallwa
  • 71
  • 1
  • 6

2 Answers2

0

In constructor:

 this.someRefName = React.createRef();

In function

let offsetTop = this.someRefName.current.offsetTop;

The other solution is:

var n = ReactDOM.findDOMNode(this);
console.log(n.offsetTop);

hey, it's works?

Piotr Żak
  • 2,046
  • 5
  • 18
  • 30
0

You can just get offsetTop from the Node.

import ReactDOM from 'react-dom';

componentDidMount() {
    var rect = ReactDOM.findDOMNode(this);
      console.log(rect.offsetTop);
  }
akhtarvahid
  • 9,445
  • 2
  • 26
  • 29
  • i am trying to get offsetTop of children components in father component's componentDidMount , but there are some children components are function component (has no componentDidMount) – Sallwa Jan 14 '20 at 13:11