Home > Enterprise >  Passing number as props in React becomes Object object
Passing number as props in React becomes Object object

Time:03-24

I am trying to send a number as props in React. When I access it it is not a number, it is Object object. I know that an object in JS is {} but in this context I expect a number not an object.

Here is the value

<button onClick={this.showNumber} value={1}>

Here is the function recieving the value

showNumber(value) {
    const userInput = document.getElementById("userInput");
    console.log("value", value);
    userInput.value = value;
  }

I have tried "1" but it do not work and feels wrong anyway. I want to pass a number, not a string.

CodePudding user response:

Set onClick to a function that calls your function with the value you want:

<button onClick={() => {this.showNumber(1)}}>one</button>
<button onClick={() => {this.showNumber(2)}}>two</button>
<button onClick={() => {this.showNumber(3)}}>three</button>

You may need to bind this.showNumber.

  • Related