Help with react js Calculator negative functionality

Hi everyone! Thanks for your help. Ive created this simple react calculator that has 4 state values of val1, val2, method, and display. the values are passed using the prop functions.

The issue right now is that it won’t pass the negative tests. Ive tried making method capable of having two methods but this actually messes up the calculations somehow.
Let me know if you see anything! I appreciate it!!

Hey! Really cool approach. I did this:

handleClick(e){
      console.log(e.target.value)
      this.setState({
        val1: this.state.val1 + e.target.value,
        display: this.state.val1
      });
    }

To try and see what value was passed to your state. It kept logging out undefined. I think this is why nothing gets displayed.

1 Like

Adding up on the previous answer:

  • I believe only <input/> has a ‘value’, not divs. I’ve checked this out also by opening the dev tools.
  • Also, you’re updating the state, so it should be like this:
handleClick(e){
      const value = e.target.textContent
       this.setState(s=>({
        val1: s.val1 + value,
        display: s.val1
      }));
    }
  • There is a weird problem called synthetic event, and if the event’s value isn’t taken out of the setState, it dies before React uses it. So I took it out.

I recommend the following approach:

  • Make a calculator of 2 numbers, then try to go further on. It will become an easier problem.

Version with just a few changes here.

2 Likes

thanks for that! helped moving the event outside the setState. One additional question if you have time, my calc is fully functional but wont pass the decimal tests (not allowing more than 1). It doesnt allow more than one but for some reason wont pass the test. Any clue what bug this is?? Thx!

I have the same issue with mine except i cant get it to not allow more than one. How did you get yours to work??

Maybe your calc doesnt pass the decimal test because it only passes one test example. Idk for sure but maybe you accounted for situations like 2..3 but not 2.3.3.4??

Nah mine doesnt handleClick if the string contains “.” and the new value is “.”

1 Like

Is there a way to set this condition in my props? This would save me a lot of time. I’ve spent over a week stuck on two tests

Edit: I went over your code. Amazing work!! I think i found my solution. Doesn’t work as it should yet so i’ll ask for help from fCC admins

1 Like

heres a copy of my codepen that has the changes I implimented. It actually made it pass less tests. I added explanations for the code. If anyone can see what is making it fail more tests, that would be great if you could explain!