Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!