why input value don't change in real time

Issue

I make a code about calculator with React. I use useRef for change value about firstref and secondref, resultref. resultref.current is correctly changed in console. But in the page, resultref.current in input tag don’t change in real time. I want to know why this is happen. Is this my fault?

import { useRef } from 'react';

const Calculator = () => {

  const firstref = useRef(0);
  const secondref = useRef(0);
  const resultref = useRef(0);

  const ClickChange = () => {
    resultref.current = Number(firstref.current) + Number(secondref.current);
    console.log(resultref.current)
  }

  return (
    <div>
      <input type="text" ref={firstref} placeholder={firstref.current} onChange={
        (e) => firstref.current = e.target.value} />
      +
      <input type="text" ref={secondref} placeholder={secondref.current} onChange={
        (e) => secondref.current = e.target.value} />

      <input type="button" value="=" onClick={ClickChange} />

      <input type="text" ref={resultref} placeholder={resultref.current} />

    </div>
  )
}

export default Calculator

every props are worked. I checked it in the conosole.

p.s I want to use placeholder. but if it makes problem, please say why it isn’t worked.

Solution

You have to set the value like this

 resultref.current.value = Number(firstref.current) + Number(secondref.current);

Answered By – Aegon

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published