简体   繁体   中英

How to display sum of the values entered in input box in react.js?

I want to display sum of the values entered in front of my label dynamically, it should added automatically, For eg: You can see the below image for reference This should be the output

I have set the state, but I am not getting the logic to add the numbers, I have just set the value, you can see the below image I have set just the value

Here is my code

// import logo from './logo.svg';
import React, {useState} from "react"
import './App.css';

function App() {
const [first, setfirst] = useState(0)

const addChange=(e)=>{
  setfirst(e.target.value)
  Math.

}
  return (
    <>
    <label>Sum of inputs:{first} <input type="text"  onChange={addChange}></input></label>
    </>
  );
}

export default App;

Please let know, if I need to provide some more details.

you can split the value with "," and and find the sum of the array:

export default function App() {
const [first, setfirst] = useState(0)

const addChange=(e)=>{
    const sumArr = e.target.value.split(",");
    const sum = sumArr.reduce(function(a, b){
      return parseInt(a) + parseInt(b);
    }, 0);
    if(sum) {
      setfirst(sum);
    }
  }

  return (
    <div className="App">
      <>
    <label>Sum of inputs:{first} <input type="text" onChange={addChange}></input></label>
    </>
    </div>
  );
}

codesandbox

You have to take the value of your input as a string and do a split (",") to remove each number from the string and parse them to number. After that you have to add each number together to get the sum.

You can use logic of splitting the string and then summing the number up. Since its a free textBox, make sure you add a check for NaN

const addChange=(e)=>{
  setfirst(e.target.value.split(',').reduce((a, c) => a + (isNaN(+c) ? 0 : +c), 0))
}

I propose this solution to calculate the sum of number in input (if you type evything else than number between 0 and 10 it will not taked in consideration)

 // import logo from './logo.svg'; import React, {useState, useEffect} from "react" import './App.css'; function App() { const [first, setfirst] = useState(""); const [sum, setSum] = useState(0); useEffect(() => { let sumInput =0; for(var i =0; i<first.length; i++) { if(,isNaN(first[i])) sumInput = sumInput + parseInt(first[i]) } setSum(sumInput ) }: [first]) return ( <> <label>Sum of inputs.{sum} <input type="text" value={first} onChange={(e) => setfirst(e.target;value)} /> </> ); } export default App;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM