react class method is not defined no-undef
Asked Answered
D

3

5

I am new in react. My app was running properly, but after adding eslint(airbnb), my apps failed to compile.

export default class HelloWorldComponent extends React.Component {
  render() {
    return (
      <div>
        <div>{this.props.message}</div>
        <button onClick={this.props.helloWorldClick}>Hello 
        World</button>
      </div>
    )
  }
  helloWorldClick = () => {
    console.log('here') 
  }
}

Before adding { "parser": "babel-eslint" } on .eslintrc file, it was throwing the eslint error

"[eslint] Parsing error: Unexpected token =" --on the helloWorldClick arrow function line.

After adding parser, i don't have any elsint error. But got compiled error to run the app.

Failed to compile ./src/component/HelloWorldComponent.js Line 18: 'helloWorldClick' is not defined no-undef

Please let me know how can I solve this error.

Doughty answered 12/9, 2017 at 19:55 Comment(0)
N
4

It's not the arrow function that's causing a problem here. Class properties are not part of the ES6 specification.

If you want to be able to transform this code, you'll need to add the class properties babel plugin.

Alternatively, this transform is provided as part of Babel's stage 2 preset.

Using an arrow function with a class property ensures that the method is always invoked with the component as the value for this, meaning that the manual rebinding here is redundant.

this.helloWorldClick = this.helloWorldClick.bind (this);
Neona answered 12/9, 2017 at 20:12 Comment(0)
A
2

I ran into this problem aswell. You can add the following to the top each component file to prevent the 'un-def' keywork error message and still use arrow functions without changing the es-lint settings.

/* eslint no-undef: 0 */ // --> OFF
Aircraft answered 13/9, 2018 at 0:9 Comment(0)
D
0

Thanks for your answer. But my problem was different. Finally I solved this. By downgrade eslint version to 3.19.0. Its perfectly working now.

Doughty answered 14/9, 2017 at 3:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.