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?
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 .
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
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.
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.
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);
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With