DEV Community

Cover image for Week 6 - Sum Two Numbers App
Mohamed Khaled Yousef
Mohamed Khaled Yousef

Posted on

3 1

Week 6 - Sum Two Numbers App

Welcome to Week 6 of React Curve

Hello developer!, glad to see you again.

This is a react-curve, open source project where I can share and start creating small UI components in the way I understood the concepts to build large scale projects .


Sum Two Numbers App

Sum Two Numbers app
This week we created a Sum Two Numbers app. The user enter two numbers in a form and result of the summation is shown in react.

To create a SumTwoNum component; We have to :

  • Create two states that hold the value of each number.
  • Create a state that holds the summation value with an initial value equal to zero.
  • Create a calculate function that calculates and updates the summation.
  • Create two inputs and handle events for each number.
  • onClick submit button, calculate method is fired and do summation.

Code

import React, {useState} from 'react';

const SumTwoNum = () => {
    const [number1, setNumber1] = useState();
    const [number2, setNumber2] = useState();
    const [summation, setSummation] = useState(0);

    function calculate() {
        setSummation(number1 + number2);
    }

    return (

       <div>
            <h2>Sum Two Numbers</h2>
            <input
                placeholder="First Number"
                type="number"
                value={number1}
                onChange={(ev) => setNumber1(+ev.target.value)}
            />
            <input
                placeholder="Second Number"
                type="number"
                value={number2}
                onChange={(ev) => setNumber2(+ev.target.value)}
            />
            <br />
            <button onClick={calculate}>Sum Two Numbers</button>
            <p>Summation  : {summation || "0"}</p> 
        </div>
    );
}

export default SumTwoNum;

Enter fullscreen mode Exit fullscreen mode

Conclusion

Thank you for reading and any contribution is more than welcome in the threads below!

Live Preview
Source Code

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more