Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to "mostly legacy" ref String Attribute?

Tags:

I was a bit surprised when I read the updated React docs about refs. While their examples on the React front page still use this.refs.textarea, they later "recommend" to not use this approach anymore.

But what's the alternative? I find too long inline code confusing and calling a function instead, like {() => this.initChartLibrary() } (the () => is required to not lose context to this) requires to build a method that gives the wrong impression of that it can be reused.

In other words, I'd still like to use the String way. But since I fear they'll deprecate it, I was wondering, if there are any other approaches?

like image 762
kraftwer1 Avatar asked May 23 '16 13:05

kraftwer1


1 Answers

As far as I'm aware the main alternative to ref strings is in fact the ES6 style callback function.

So:

<textarea ref="myTextArea">
...
</textarea>

// Where refs are then accessed by `this.refs.myTextArea` to perform any operations

Becomes, in a basic form:

<textarea ref={ (ref) => this.myTextArea = ref }>
...
</textarea>

// Where refs are then accessed by `this.myTextArea`

This can be pretty powerful because the ref attribute in React automatically receives the referenced component as a parameter, which allows us to immediately implement our callback operations on it if we'd like. This can be used in a simple form, as above, to assign that reference to this.myTextArea, or as you've probably noticed in the docs, you can be a bit more direct and do things like:

<input 
  ref = {(input) =>
          { if (input != null) {input.focus()} }
  } /> 

That being said, although this sometimes means you can express your code in the fewest number of lines, it definitely sacrifices readability. If you are just looking to save a reference to the component for use in an event handler (as is very commonly the case) using a ref string is honestly still the cleanest way to do so.

I really wouldn't anticipate them to be deprecated without warning, as they are used pretty heavily in React & remain convenient, but if they ever are your best bet would be a straightforward refactor with a simple (ref) => this.myRef = ref then accessing your refs by this.myRef.

like image 141
Brad Colthurst Avatar answered Oct 03 '22 17:10

Brad Colthurst