Calculator


So I had to re-do this project. And trust me, trully re-do.
If you haven't checked you can see my github calculator project and you'll see that this one is quite different, the reason? My oldest one (github) is not using React, and this one is!

To make this calculator i had to create Buttons and Input components that were not required in my oldest one. But let me show you some logic first.


Button and Input

My button component was created so it can recieve the input information, here:

const Button = ({ pressedButton, handleClick }) => {
  return(
    <Container>
    <button
      className="wrapper"
      onClick={() => handleClick(pressedButton)}
    >
      {pressedButton}
    </button>
    </Container>
  );
}

And my input component was created to show the current and the last result:
const Input = ({ current, latest }) => {
  return (
    <Container>
      <div className="wrapper">
        <div className="latest">
          <h1>{latest}</h1>
        </div>

        <div className="current">
          <h3>{current}</h3>
        </div>
      </div>
    </Container>
  );
};

All of this was used in my main JSX for this page. Now let's move on to it!


Calculator

To make this happen i used the useState react component to set values so I could make operations with it.
So, the calculation could be done by 2 different ways, or I did a switch case (such as the github project) or I could use a new lib to do it. I chose the lib!
It's called "mathjs" and the way that it works is this: you give it a string with operators and it will calculate for you. So in my logic i did:
const [current, setCurrent] = useState("");
const [latest, setLatest] = useState("");

const intoCurrent = (newInput) => {
  setCurrent((current) => [...current, newInput]);
}

const calculateResult = () => {
  const input = current.join("");
  setLatest(math.evaluate(input));
};

In other words, i just did a long string and used the "math" component to calculate it. Quite simple and different from what i already have done.

As you may notice the calculator also have "AC" and "DEL" buttons, the AC clears the inputs and results and DEL delete the last input that you did. Here's how:
const eraseNumber = () => {
  const input = current.slice(0,-1);
  setCurrent(input);
};

const resetInput = () => {
  setCurrent("");
  setLatest("");
};
DEL is "eraseNumber" and AC is "resetInput"

With that the one thing missing is the main JSX html organization, here's an exemple:
<Button pressedButton="AC" handleClick={resetInput}/>
<Button pressedButton="DEL" handleClick={eraseNumber} />
<Button pressedButton="÷" handleClick={intoCurrent} />
<Button pressedButton="*" handleClick={intoCurrent} />



With that I was able to re-write and existing code and learn new methods. I hope you have enjoyed the reading!

Don't forget to check the links!
by Thales Fornazari