10 React Challenges for Beginners - Lesson #6

React Challenge: Adding Calculator

Storing data in a front-end application and reusing the stored data throughout the application or app component, is an essential piece of modern front-end applications.

In this React challenge, you'll build a simple calculator which displays the sum of two numbers.

For this challenge, you will receive two numbers from an input element and add both numbers. Display the sum of these numbers on the same page. The main tasks of this challenge are:

  • Store input numbers.
  • Add numbers.
  • Display the sum on the page.

Fork this CodeSandbox to get started quickly: https://codesandbox.io/s/q8nxoyqn49

The base CodeSandbox contains styling for the application as well as the basic required elements of the application. Feel free to use those.

Here's what the final application looks like:

As a bonus, try to carry out other arithmetic operations and assign them to buttons in the application. For instance, add multiply, subtract, and divide buttons.

This challenge relies heavily on React's ability to store component data in state and reuse this data throughout the component.

This challenge is completed in 3 steps:

  • Create state for the two inputs.
  • Handle addition of numbers.
  • Display the calculated sum.

Utilize the useState React hook to create state variables in the functional component. Import useState at the top of the App() component with:

jsx
import { useState } from 'react';

In the App() component, create three state variables destructured from useState to:

  • Hold the value of the first number.
  • Hold the value of the second number.
  • Store the value of the sum.

Do this with:

jsx
// import  ...

function App() {
  const [number1, setNumber1] = useState(0);
  const [number2, setNumber2] = useState(0);
  const [total, setTotal] = useState(number1 + number2);

  return (
    // Return component's JSX
  )
}

We set the default values of the numbers to 0 and the total to the sum of both numbers, which by default is zero as well.

Now we can store and retrieve the value of the numbers to be added in state, proceed to assign these data values to the input element. Also, the value of the data stored in state would be updated from the input using the onChange input event. In the returned JSX of the App() component, specify the value and onChange attributes of the input elements with:

jsx
// import ...

function App() {

  // Component variables

  return (
    <div className="App">
      <h1>Adding Two Numbers</h1>

      <div className="number-inputs">
        <input
          type="number"
          value={number1}
          onChange={e => setNumber1(+e.target.value)}
          placeholder="0"
        />
        <input
          type="number"
          value={number2}
          onChange={e => setNumber2(+e.target.value)}
          placeholder="0"
        />
      </div>

      <button>Add Them!</button>

      <h2>{total}</h2>
    </div>
  );
}

With these, we specified the value of the input elements as well as update the value displayed as the total from a static zero in the starter code to total which is pulled from state.

We are currently able to update the stored numbers in state, from the same state, these numbers can be pulled and manipulated.

Proceed to create a function in the App() component to add the two numbers with their values pulled from the respective state variables. Do this with:

jsx
// import ...

function App() {
  // State variables
  const [number1, setNumber1] = useState(0);
  const [number2, setNumber2] = useState(0);
  const [total, setTotal] = useState(number1 + number2);

    // Function to add numbers and update total in state
  function calculateTotal() {
    setTotal(number1 + number2);
  }

  return (
    // Returned JSX
  );
}

Once the calculateTotal function is called, the first and second numbers are added, while the sum is updated in total.

Update the "Add Them!" button to call this function when clicked. Do this with:

jsx
// import ...

function App() {

  // Component variables

  return (
    <div className="App">
      <h1>Adding Two Numbers</h1>

      <div className="number-inputs">

        {/* Input elements */}

      </div>

      <button onClick={calculateTotal}>Add Them!</button>

      <h2>{total}</h2>
    </div>
  );
}

With this, once you click the button, both numbers are added and the sum is displayed on the page.

Here's what the final application looks like:

You can find the completed CodeSandbox.

In this React challenge you built a simple calculator which adds two numbers and displays the sum.

Have you got questions, suggestions, and comments? We'd love to see them in the comment section. Happy keyboard slapping!

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)