11

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>
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212

2 Answers2

19

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
  • 270,417
  • 55
  • 406
  • 400
-2

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
  • 12,042
  • 16
  • 52
  • 116
  • 6
    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 – whallz Dec 22 '20 at 17:41