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);
}
}
Reference errors in Javascript are mainly thrown when an attempt is made to reference a variable that does not exist or is out of scope. Therefore, in the majority of cases, a ReferenceError can be fixed by making sure that the referenced variable is defined correctly and is being called in the correct scope.
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' .
The most common reason behind the error "Uncaught ReferenceError: $ is not defined" is executing the jQuery code before the jQuery library file has loaded. Therefore make sure that you're executing the jQuery code only after jQuery library file has finished loading.
A not defined error is when we did not declare the variable and tried to call that variable. In JavaScript, we can declare variables without adding const , let , or var , and we won't get an error of undefined or not defined . This can be seen in the code below.
EDIT Just saw the comments and that zerkms already provided you with the solution. I'll leave my answer for clarification purposes.
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.`
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With