Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

576
Visualizações
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 referenceThis 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.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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 .

about 4 years ago · Juan Pablo Isaza Relatório

0

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))
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda