Randy_Johnson's avatar

ReactJS Adding int to current int not working

I am building a calc in reactjs,. just copying the windows scientific calc. There are many buttons so I am trying to keep everything together so I stuck all button data inside an array of objects.

I am trying to add an int to the end of the current int, eg, 1, = 12. The logic below should work, I am sure, but I guess I am missing something.

{ id: 27, value: '2', function: () => { let x = current.toString() + buttons[27].value; setCurrent(x) }, className: 'bg-yellow-200 hover:bg-yellow-400' },
0 likes
5 replies
Tray2's avatar

Of course, the value is the string '2' not the number 2.

You need to use parseInt.

let newValue = parseInt(item.value) + 1;
Randy_Johnson's avatar

@Tray2 It seems to be something more than this.

In JS playground I do this

let x = '1';
let y = '2';
let z = x + y;
let a = z + '1'

console.log(a)

Okay, everything is working how it should in the code above.

So in my code I have two strings, and pushing them together works fine. Its just that adding more to it after that is the problem. Just like how you click numbers on a calculator and the number is pushed into the section at the top to have a complete number, this is my goal.

I don't want to calculate I just want for display.

Tray2's avatar

@Randy_Johnson Then you need to treat them as strings and not ints.

let a = 1;
let b = 2;

let sum = a + b ; //3

let concateString = a.toString() + b.toString(); // = '12'
Randy_Johnson's avatar

I know, they are strings, but I think it has something to do with how react works which is causing problems.

Randy_Johnson's avatar
Randy_Johnson
OP
Best Answer
Level 8

Okay, it was weird, but I fixed it. I have to two variables, one being typical and another being useState. I have to set the typical variable and then set it to use state, for some reason, grabbing the useState var, updating it and placing it back it just doesn't want to do it. Strange behavior.

Please or to participate in this conversation.