Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

172
Vistas
Show counter onChange input box with a current defaultValue in React

How do I get the value to be the inital value first form the data of the API and then change when the user starts typing or deleting text?

import React, {useState} from 'react'

const MyInput = () => {
  const [counter, setCounter] = useState(0)

  const initial = dataFromApi.length

  const total = 1000

  const counterChange = (e) => {
    setCounter(initial.length + e.target.value.length)
  }

  return(
    <>{counter}/{total}<input defaultValue={dataFromApi} onChange={counterChange}/></>
  )

}

export default MyInput

https://codesandbox.io/s/compassionate-napier-3nekx?file=/src/App.js

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Pass the initial length to the useState hook

const initial = dataFromApi.length
const [counter, setCounter] = useState(initial)

If you expect your API data to change you could use a useEffect hook to reset the length state when API data changes

useEffect(() => {
  setCounter(dataFromApi.length);
}, [dataFromApi.length]);

and there's no need to add the initial value in the onChange handler if you want to show the current length of the entered text

setCounter(e.target.value.length)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda