Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element reference without using refs in react

Tags:

reactjs

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?

like image 239
dagda1 Avatar asked Aug 15 '16 06:08

dagda1


People also ask

How do you get the current ref In react?

When the ref attribute is used on an HTML element, the ref created in the constructor with React.createRef() receives the underlying DOM element as its current property. When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current .

How useref () and ReFS (aka references) work in react?

React.useRef () is a hook that creates mutable values persisted between component renderings and references DOM elements. In this post, you’ll learn how useRef () and refs (aka references) work in React. Interesting demos included. 1. Mutable values 2. Access DOM elements 3. Updating references restriction 4. Summary 1. Mutable values

Can you pass a ref to a functional component in react?

See useImperativeHandle in action in our React Hooks reference guide. As stated earlier, you shouldn’t pass a ref to a functional component, but you can create and use refs within functional components, as seen below: Occasionally, you may want to access a child’s DOM node from a parent component.

What are props and ReFS in react?

Refs and the DOM – React Refs and the DOM Refs provide a way to access DOM nodes or React elements created in the render method. In the typical React dataflow, props are the only way that parent components interact with their children.


1 Answers

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() {
    const dimensions = ReactDOM.findDOMNode(this).getBoundingClientRect();
    console.log(dimensions);
},
like image 147
Ori Drori Avatar answered Oct 08 '22 23:10

Ori Drori