Callback refs as componentDidMount in stateless functions in React


You might think that when developing user interfaces with React and if you want to e.g. apply jQuery method to an element, you must abandon your beloved stateless function in favor of class-based component, directly or indirectly via higher-order components, because stateless function doesn’t have componentDidMount life-cycle hook. You are wrong, you can use callback refs for that where you are given DOM instance of that element.

So let’s say you are using Semantic-UI toolkit which provides jQuery methods to bootstrap functionalities like modals, accordions, tabs, etc. that needs to be called after node’s rendered and it’s DOM instance is available. So if you want to apply accordion functionality, you can do it like this.

<div className="ui styled fluid accordion" ref={el => $(el).accordion()}>
  <div className="title">
    <i className="dropdown icon"></i>
    Title
  </div>
  <div className="content">
    Content
  </div>
</div>

I use this approach quite often. But I stick to some ground rules while using it: (1) in callback ref I only manipulate with referenced element, because if I manipulate with other elements, there might be bugs due to other elements not being rendered yet and (2) I keep lines of code in callback ref as minimum as possible, preferably one-line.