How to Get a React Component’s Element
Publikováno: 14.5.2018
JSX is an amazing pseudo-language for React, and if I’m honest, it’s what brought me to love React so much. Using React without JSX is cumbersome and frustrating, while using JSX is such an easier way to express your code. One drawback of JSX, however, is that it makes accessing component elements indirect, if not […]
The post How to Get a React Component’s Element appeared first on David Walsh Blog.
JSX is an amazing pseudo-language for React, and if I’m honest, it’s what brought me to love React so much. Using React without JSX is cumbersome and frustrating, while using JSX is such an easier way to express your code. One drawback of JSX, however, is that it makes accessing component elements indirect, if not difficult.
The truth is that accessing a component’s own elements is actually much easier than most think. Let’s look at how a component method can access its own DOM node with JavaScript:
Method 1: react-dom
react-dom provides a findDomNode
method for finding the component’s node:
// Get ReactDOM import ReactDOM from "react-dom"; // In your component method class MyComponent extends Component { myMethod() { const node = ReactDOM.findDOMNode(this); } }
With ReactDOM.findDOMNode(this)
, you can get the widget’s main node, and from there you can use typical DOM methods:
const node = ReactDOM.findDOMNode(this); // Get child nodes if (node instanceof HTMLElement) { const child = node.querySelector('.someClass'); }
This mixes a bit of React and basic JavaScript DOM manipulation.
Method 2: ref
Another method of getting DOM nodes is by using ref
s; an example usage is detailed in my React and autofocus post:
class MyComponent extends Component { // The element we want to retrieve _input: ?HTMLInputElement; // .... componentDidUpdate() { this._input.focus(); } render() { return ( <div> <input ref={c => (this._input = c)} /> </div> ); } } }
Adding a ref
attribute to the element you want a handle on is a more React-centric approach to getting a handle on an element. Both strategies work well so choose whichever you prefer!
The post How to Get a React Component’s Element appeared first on David Walsh Blog.