How to get offsetTop of a React Child with TypeScript

Viewed 601

How to get a React children offsetTop using Typescript ?

Here my component:

export default class FadeIn extends Component {
  private onScroll = () => {
    React.Children.forEach(this.props.children, child => {
      // Get the child's offsetTop here and do stuff with
    })
  }

  public componentDidMount() {
    window.addEventListener('scroll', this.onScroll)
  }

  public componentWillUnmount() {
    window.removeEventListener('scroll', this.onScroll)
  }

  public render() {
    return this.props.children
  }
}

I already tried to:

  • use ReactDOM.findDOMNode(child) but I get Argument of type 'ReactChild' is not assignable to parameter of type 'ReactInstance'. Type 'string' is not assignable to type 'ReactInstance'
  • use getBoundingClientRect but I get Property 'getBoundingClientRect' does not exist on type 'ReactChild'. Property 'getBoundingClientRect' does not exist on type 'string'
  • cast child to ReactElement<any>

Any idea ?

1 Answers

1.try to send the ref to the Parent Component

2.save the refs into variable or state

3.and then in componentDidMount method, you can get the child component height by getBoundingClientRect.

Related