Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To add two numbers in react js, use the + addition operator it will add if your value datatype is a number else if your value datatype is string first convert it using parseInt() and then perform addition operation.

In the following example, we will take the sample numbers, and strings and perform add operation using the + addition operator.

Adding Two numbers example

let num1 = 30;
let num2 = 34;

num1 + num2; // 64

Adding Two string numbers example

let num1 = "30";
let num2 = "34";

parseInt(num1) + parseInt(num2); // 64

Today, I’m going to show you How do i add two numbers in react js, as mentioned above here, I’m going to use the + addition operator.

Let’s start today’s tutorial how do you add two numbers in react js?

In this example, we will do

  1. take an example of a number and string number state
  2. adding two numbers example
  3. adding two string numbers example
  4. print the output on the page screen
import React, { useState } from "react";
export default function App() {
  const [firstNum, setFirstNum] = useState(24);
  const [secondNum, setSecondNum] = useState(24);

  const [firstStr, setFirstStr] = useState("24");
  const [secondStr, setSecondStr] = useState("24");

  return (
    <div className="App">
      <h1>{`adding two numbers example`}</h1>
      <p>{firstNum + secondNum}</p>

      <h1>{`adding two string numbers example`}</h1>
      <p>{parseInt(firstStr) + parseInt(secondStr)}</p>
    </div>
  );
}

In the above react js example, we have taken the sample numbers and string numbers state, and perform adding two numbers example, and adding two string numbers example.

I hope it helps you, All the best đź‘Ť.