1

Beginner question struggling with React Component implementation. I have tried everything in the cookbook on this error but no luck.

Expected 'this' to be used by class method 'aaaa'

What is wrong with his code:

import React from 'react';

class TestStuff extends React.Component {
    constructor(props) {
        super(props);
        this.aaaa = this.aaaa.bind(this);
    }

    aaaa() {
        console.log('dddddd');
    }

    render() {
        return <div>test</div>;
    }
}

export default TestStuff;

enter image description here

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Kid
  • 1,869
  • 3
  • 19
  • 48
  • Does this answer your question? [Expected 'this' to be used by class method](https://stackoverflow.com/questions/44249478/expected-this-to-be-used-by-class-method) – Emile Bergeron Dec 15 '20 at 18:33
  • I don't think you're defining the function properly. Try ```const aaaa = () => { console.log('dddddd'); }``` – Stephen Taylor Dec 15 '20 at 18:37
  • @StephenTaylor this is a `React.Component` I'm suppose to `bind` the function in constructor I think what you propose is for functional components – Kid Dec 15 '20 at 18:41
  • @EmileBergeron I do `bind` in the constructor so my Q is not a duplicate like you proposed – Kid Dec 15 '20 at 18:43
  • @Kid look at the other answers in the linked thread, it's simply an eslint rule which you could ignore or disable, or change your code to conform without any real impact either way. – Emile Bergeron Dec 15 '20 at 18:51
  • @EmileBergeron it's not an [Eslint rule error](https://snipboard.io/BkYiZw.jpg). I just made this questions simpler removing code that was not responsible. – Kid Dec 15 '20 at 19:04
  • @Kid it is. It's even visible in the screenshot you shared: `eslint(class-methods-use-this)`. It's possibly just integrated in both VS Code and Create-React-App, making it seems like it's a critical error in the build step. – Emile Bergeron Dec 15 '20 at 19:10

1 Answers1

1

The warning is just saying, I see that you have this method in this class but it's not using any properties in the class. So either make it a static method or access a class property inside the method.

https://eslint.org/docs/rules/class-methods-use-this

SamMade
  • 13
  • 3
  • I do use [use](https://snipboard.io/tTFu6C.jpg) the method I just made this questions simpler removing code that was not responsible – Kid Dec 15 '20 at 18:47
  • @kid you use the method _but the method does not use the class_, that's what the warning is saying. – Emile Bergeron Dec 15 '20 at 18:52
  • it's not a warning if you use the method or not. The warning is saying, the method `aaaa` needs to access class properties (if you use properties like `this.someVariable`, if you don't use that then just put a `static` keyword in front of the method. – SamMade Dec 15 '20 at 19:01