Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react class method is not defined no-undef

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.

like image 658
Mahfuja nilufar Avatar asked Sep 12 '17 19:09

Mahfuja nilufar


People also ask

Is not defined no undef in react?

The React. js error "X is not defined react/jsx-no-undef" occurs when we forget to import a function, class or a variable in our code before using it. To solve the error, make sure to import the value before using it in your code, e.g. import {myFunc} from 'my-package' .

Can we use jQuery in react JS?

Yes, we can use jQuery in ReactJs.

How do you make a functional component react?

We can create a functional component to React by writing a JavaScript function. These functions may or may not receive data as parameters. In the functional Components, the return value is the JSX code to render to the DOM tree. Example: Program to demonstrate the creation of functional components.


2 Answers

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);
like image 103
TRomesh Avatar answered Sep 28 '22 05:09

TRomesh


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
like image 24
Matt Catellier Avatar answered Sep 28 '22 04:09

Matt Catellier