0

I have a class Display that uses values from a helper.js file for all its data and utilities. I am facing a problem where I need to call a method of the class from a function helper.js. Here is what I am trying to achieve:

class Display extends Component {
      constructor(props) {
        super(props);

        this.imgHandler = this.imgHandler.bind(this);
      }

      imgHandler() {
        const displayValues = this.getValues();

        this.setState({
          displayValues
        });
      }
    }

helper.js

function renderIcon() {
  return (
    <img onClick={addHandler} />
  )
}

I tried creating an instance of Display in helper.js and setting the onClick handler in renderIcon as follows:

const display = new Display();
<img onClick={display.imgHandler}>

But doing this gave me an error:

ReferenceError: can't access lexical declaration display before initialization

Could I please get some help with accomplishing the above? Thanks!

craig-nerd
  • 718
  • 1
  • 12
  • 32
  • 1
    Creating an instance of Display in helper.js creates a different Display object than the one used by React anyway. – Randy Casburn Jun 29 '19 at 16:01
  • Possible duplicate of [How do I include a JavaScript file in another JavaScript file?](https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file) – Randy Casburn Jun 29 '19 at 16:03
  • Where are you calling `renderIcon`? – Bergi Jun 29 '19 at 16:20
  • @Bergi I am calling `renderIcon` in a child component of `Display` – craig-nerd Jun 29 '19 at 17:14
  • @RandyCasburn The question you linked is asking for a function in a javascript file and not a class method. When I try this approach, I get a `unexpected token` error – craig-nerd Jun 29 '19 at 17:21
  • With the little bit of info you've provided here, this appears to be a module import/export issue more so than anything else. Therefore, the dup is about getting that correct regardless of Class function or whatever. – Randy Casburn Jun 29 '19 at 17:25
  • @Jspake Can you show that code, please? Probably you should pass a [reference to an instance method](https://stackoverflow.com/q/20279484/1048572) from the `Display` component into your child component, and from there to `renderIcon` via a parameter. – Bergi Jun 29 '19 at 17:52

1 Answers1

0

You should not call the argument in the constructor this, the error suggests you are accessing this before it's ready to be used, which it would be fine to use anytime after super is called. Just rename it to props or something like that.

Make sure to update any this references in the constructor, except for the bind, it should be fine there

Logan Murphy
  • 6,120
  • 3
  • 24
  • 42
  • Thanks for your answer. I made an error with in my sample code in the question. I am indeed using `props` in the constructor – craig-nerd Jun 29 '19 at 17:16