CyberJunkie
CyberJunkie

Reputation: 22674

React get offset of element outside the component

I am trying to get the offsetTop, offsetLeft, offsetHeight, etc of an element that is outside my React component and pass the values as inline CSS to the React component.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  const top = document.getElementById("div1").offsetTop;
  const left = document.getElementById("div1").offsetLeft;
  const bottom = document.getElementById("div1").offsetHeight;

  render() {
    return (
      <div 
         className="example"
         style={
           top: top,
           left: left,
           bottom: bottom,
         };
       ></div>
    );
  }
}

The code above gives undefined for top, left, and bottom offset values.

Upvotes: 1

Views: 4137

Answers (2)

Ray Yee
Ray Yee

Reputation: 36

Confirm the outside element already mount

class MyComponent extends React.Component {
    state = { top: 0, left: 0, bottom: 0 }
    componentDidMount() {
        const top = document.getElementById( "div1" ).offsetTop;
        const left = document.getElementById( "div1" ).offsetLeft;
        const bottom = document.getElementById( "div1" ).offsetHeight;
        this.setState( { top, left, bottom } )
    }

    render() {
        const { top, left, bottom } = this.state;
        return (
            <div 
                className="example"
                style={
                   top: top,
                   left: left,
                   bottom: bottom,
                }
            ></div>
        );
    }
}

Upvotes: 2

wrsx
wrsx

Reputation: 789

They are undefined because it looks like you want top, left, and bottom to be class properties.

Place them in your constructor:

constructor(props) {
    super(props);
    this.top = document.getElementById("div1").offsetTop;
    this.left = document.getElementById("div1").offsetLeft;
    this.bottom = document.getElementById("div1").offsetHeight;
}

Access them with {this.top}, {this.left} etc.

Upvotes: 1

Related Questions