Home > Software design >  Show counter onChange input box with a current defaultValue in React
Show counter onChange input box with a current defaultValue in React

Time:10-24

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

CodePudding user response:

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)

  • Related