Adam Schwarcz
Adam Schwarcz

Reputation: 487

Export variable from componentDidMount

How do I export the "x" variable from componentDidMount so i can use it in the render section? I am trying to check for the x position of my div.

import React from 'react';

class Icon extends React.Component {
  constructor(props) {
    super(props);
    this.selector = React.createRef();
  }

  componentDidMount = () => {
    var rect = this.selector.current.getBoundingClientRect();
    var x = rect.top;
    console.log(x);
   };

  render() {
    return (
      <div className="icon" ref={this.selector}>
        <p>x: {x} & y:</p>
      </div>
    );
  }
}

export default Icon;

Upvotes: 1

Views: 366

Answers (2)

rorra
rorra

Reputation: 9693

As they said before, most of the time you want to track the state of the data being drawn, and if the state changes, let react to automatically draw the data change

but if you don't want to track state for any reason, you can use an attribute, instead of using x, use this.x

import React from 'react';

class Icon extends React.Component {
  constructor(props) {
    super(props);
    this.selector = React.createRef();
  }

  componentDidMount = () => {
    var rect = this.selector.current.getBoundingClientRect();
    this.x = rect.top;
    console.log(this.x);
   };

  render() {
    return (
      <div className="icon" ref={this.selector}>
        <p>x: {this.x} & y:</p>
      </div>
    );
  }
}

export default Icon;

Upvotes: 0

kind user
kind user

Reputation: 41913

Why not to use the state?

constructor(props) {
   super(props);
   state = {
      x: null,
   };

   this.selector = React.createRef();
}

then inside lifecycle:

componentDidMount = () => {
   var rect = this.selector.current.getBoundingClientRect();
   this.setState({ x: rect.top });
};

and finally inside render:

<p>x: {this.state.x} & y:</p>

Upvotes: 1

Related Questions