How to reference DOM elements in React

Learn how to reference DOM elements in React

When building applications, React is good at extracting the DOM from you.

But what if you want to access the DOM elements represented by React components?

Maybe you have to add a library that directly interacts with the DOM like a chart library, maybe you need to call some DOM API or focus on elements.

Regardless of the reason, a good practice is to ensure that there is no other way to directly access the DOM.

In the component's JSX, you can use the following attributes to assign references to DOM elements to component attributes:

ref={el => this.someProperty = el}

Put it in context, for example usingbuttonelement:

<button ref={el => (this.button = el)} />

buttonRefer to the properties of the component, the life cycle method of the component (or other methods) can use this property to interact with the DOM:

class SomeComponent extends Component {
  render() {
    return <button ref={el => (this.button = el)} />
  }
}

In functional components, the mechanism is the same, just avoid usingthis(Because it does not point to the component instance), but use attributes:

function SomeComponent() {
  let button
  return <button ref={el => (button = el)} />
}

Download mine for freeResponse Handbook


More response tutorials: