Home > Software design >  How to set initial value on useRef<HTMLInputElement> - ReactJs Typescript
How to set initial value on useRef<HTMLInputElement> - ReactJs Typescript

Time:12-11

I would like to set a number as initial value on useRef<HTMLInputElement>.

I don't need to use useState<number>() because the field is a simple counter.

Here is my typescript code:

const MyComponent = () => {

  const productAmountRef = useRef<HTMLInputElement>();

  const handleReduceClick = () => {
    productAmountRef.current.value -= 1;
  }

  const handleAddClick = () => {
   productAmountRef.current.value  = 1;
  }

  return (
    <>
      <SomeWrapper>

        <ReduceButton onClick={handleReduceClick}/>

          <input disabled={true} ref={productAmountRef}/>

        <AddButton  onClick={handleAddClick}/>


      </SomeWrapper>
    </>
  )

}

For obvious reasons, when the onClick function is triggered, the value is a NaN.

My doubt is, how can I set a Initial Value on useRef<HTMLInputElement>? As I said and as you saw, it need to be a number.

Is this possible?

CodePudding user response:

Set the initial value using the defaultValue attribute:

<input disabled={true} ref={productAmountRef} defaultValue={3} />

Or use useState() and render the number without the use of an input:

const MyComponent = () => {

  const [productAmount, setProductAmount] = useState(0);

  const handleReduceClick = () => {
    setProductAmount(val => val - 1);
  }

  const handleAddClick = () => {
   setProductAmount(val => val   1);
  }

  return (
    <SomeWrapper>
      <ReduceButton onClick={handleReduceClick}/>

      <div>{productAmount}</div>

      <AddButton  onClick={handleAddClick}/>
    </SomeWrapper>
  )
}
  • Related