dagda1 dagda1 - 3 months ago 27
React JSX Question

Get element reference without using refs in react

I am told refs are likely to be deprecated.

How then could I achieve the following, considering this code:

export default class DemoAxis extends Component {
componentDidMount() {
const el = this.refs.line;

const dimensions = .getDimensionsFromElement(el);
}

render() {
return (
<div ref="line">
</div>
);
}


I need a reference to the line div to get dimensions from it.

I know there is a ref callback, should I be using that?

Answer

Only string refs are considered for deprecation, you can still use callback refs:

export default class DemoAxis extends Component {
    componentDidMount() {   
      const dimensions = .getDimensionsFromElement(this._line);
    }

    render() {
      return (
        <div ref={ (ref) => this._input = ref }>
        </div>
      );
    }
}

Or in your case, you don't need a ref, just get the DOM node from the component this, using ReactDOM.findDOMNode (demo):

componentDidMount() {
    var dimensions = ReactDOM.findDOMNode(this).getBoundingClientRect();
    console.log(dimensions);
},