9

I am doing this in react native code, eslint is showing error for line ref="drawer"

[eslint] Using string literals in ref attributes is deprecated.

What is correct way to do this.

<DrawerLayoutAndroid
                drawerWidth={300}
                ref="drawer"
                drawerPosition={DrawerLayoutAndroid.positions.Left}
                renderNavigationView={() => navigationView}
            </DrawerLayoutAndroid>
Flimzy
  • 68,325
  • 15
  • 126
  • 165
Khemraj Sharma
  • 52,662
  • 21
  • 188
  • 195

2 Answers2

15

You need to make use of ref callback pattern as string refs are deprecated.

<DrawerLayoutAndroid
            drawerWidth={300}
            ref={(ref) => this.drawer = ref}
            drawerPosition={DrawerLayoutAndroid.positions.Left}
            renderNavigationView={() => navigationView}
        </DrawerLayoutAndroid>

(ref) => this.drawer = ref is an arrow function syntax, you can simplify it similar to

constructor(props) {
   super(props); 
   this.setRef = this.setRef.bind(this);
}
setRef(ref) {
   this.setRef = ref;
}

...
ref={this.setRef}

Check this answer for more info

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

Shubham Khatri
  • 246,420
  • 52
  • 367
  • 373
-1

you can wrap them with curly braces to indicate it's valid JS syntax

<DrawerLayoutAndroid
            drawerWidth={300}
            ref={'DRAWER'}
            drawerPosition={DrawerLayoutAndroid.positions.Left}
            renderNavigationView={() => navigationView}
        </DrawerLayoutAndroid>
Isaac
  • 10,467
  • 12
  • 39
  • 97
  • 5
    Even if you add curly braces es-lint errors will show the same – Tino Jose Thannippara Jan 10 '19 at 10:40
  • 1
    @TinoJoseThannippara: I'm pretty sure they wont but it could be due to your code editor taking some time for refreshing. You can try to reopen the page – Isaac Jan 10 '19 at 10:43
  • question is asking the correct way to solve the error eslint is showing, and not how to workaround the eslint rule – agbb Dec 22 '20 at 17:41