0

I'm new to react.js and I'm trying to math.random a number and put it in this.props.firstCard property, but it returns undefined. I tried some variables but only result is undefined or syntax error. Code:

handleClick() {
let firstCard = this.state.isFirstCardChosen;
function chooseCard() {
  return Math.floor(Math.random() * (80 - 1) + 1);
}
if (firstCard == false) {
  this.props.firstCard = chooseCard;
  console.log(this.props.firstCard);
}
}

What's wrong with this one? Thanks in advance.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
zaebalo
  • 147
  • 2
  • 12
  • sry there's a `this.props.firstCard == chooseCard;` instead of 'this.props.firstCard = chooseCard;', which returns 'not extensible' error. – zaebalo Dec 27 '16 at 01:02
  • this.props is immutable. You cannot modify it. Go through some react tutorials on setState and props – Martin Dawson Dec 27 '16 at 01:10

2 Answers2

0

I'm going to hazard a guess and suggest that

if:

the problem isn't just one caused by the fact you are trying to mutate props (props are immutable).

and:

You're using ES2015 class syntax

then

the problem may be that your handleClick method isn't properly bound to the component state so the call to this.props returns undefined.

To solve this you can bind the handleClick in the constructor as follows:

constructor (props){
  super(props);
  this.handleClick = this.handleClick.bind(this);
}
Community
  • 1
  • 1
Pineda
  • 7,435
  • 3
  • 30
  • 45
0

As everyone else has said the props is immutable. Also make sure you are setting props correctly and binding your handleClick function in your constructor i.e:

constructor(props) {
    super(props);
    his.handleClick = this.handleClick.bind(this);
}
nickmcblain
  • 155
  • 1
  • 2
  • 12