16

I am trying to call shuffleCards when the upon a click event in a ReactJs component. However, I am receiving the following error:

Uncaught ReferenceError: shuffleCards is not defined

Here's my code:

constructor(props) {
    super(props);

    this.state = {
        count: 0
    };
}

shuffleCards(array) {
    var i = array.length,
        j = 0,
        temp;

    while (i--) {
        j = Math.floor(Math.random() * (i+1));

        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

handleClickEvent(event) {
    var cards = [
        {txt: "A",
        isDisplayed: false},
        {txt: "B",
        isDisplayed: false},
        {txt: "C",
        isDisplayed: false}
    ];
    if (this.state.count == 0) {
        cards = shuffleCards(cards);
    }

}
2
  • 16
    this.shuffleCards Commented Sep 21, 2016 at 23:00
  • @zerkms wow can't believe i didnt think of doing that. it worked. thanks! Commented Sep 21, 2016 at 23:13

3 Answers 3

32

EDIT Just saw the comments and that zerkms already provided you with the solution. I'll leave my answer for clarification purposes.


Your problem is that inside the handleClickMethod, you are calling shuffleCards instead of this.shuffleCards

shuffleCards(array) {
  // ...
}

handleClickEvent(event) {
    // ...
    if (this.state.count == 0) {
        cards = this.shuffleCards(cards); // here you should use `this.`
    }
}

The reason is because shuffleCards method is defined on your component, which is accessible from its methods via the this property.

If you defined shuffleCards within the handleClickMethod, then you could call it without accessing this:

handleClickEvent(event) {

    function shuffleCards(array) {
      // ...
    }

    // ...
    if (this.state.count == 0) {
        cards = shuffleCards(cards); // here you don't need `this.`
    }
}
Sign up to request clarification or add additional context in comments.

Comments

6

Would this work for you? Demo here: http://codepen.io/PiotrBerebecki/pen/qaRdgX

You missed this when referring to shuffleCards in the handleClickEvent method.

shuffleCards(array) {
  // logic here
}

handleClickEvent(event) {
  cards = this.shuffleCards(cards);
}

render() {
  return (
    <button onClick={this.handleClickEvent.bind(this)}>Click me</button>
  );
}

Comments

0

I had the same problem.

And i upgrade "react-scripts" and fix this problem.

Probaply fix this.

npm i react-scripts

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.