Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set initial value on useRef<HTMLInputElement> – ReactJs + Typescript

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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>
  )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading