Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing number as props in React becomes Object object

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading