Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

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

In the following example, we will take the sample numbers, and strings and perform subtract operations using the - subtraction operator.

Subtracting Two numbers example

let num1 = 30;
let num2 = 34;
num2 - num1; // 4

Subtracting Two string numbers example

let num1 = "30";
let num2 = "34";
parseInt(num2) - parseInt(num1); // 4

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

Let’s start today’s tutorial on how do you subtract two numbers in react js.

In this example, we will do

  • take an example of a number and string number state
  • subtracting two numbers example
  • subtracting two string numbers example
  • 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(20);
  const [firstStr, setFirstStr] = useState("24");
  const [secondStr, setSecondStr] = useState("20");
  return (
    <div className="App">
      <h1>{`subtracting two numbers example`}</h1>
      <p>{firstNum - secondNum}</p>
      <h1>{`subtracting 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 performed subtracting two numbers example, and subtracting two string numbers example.

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

Output