Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the value of an input field on change of a field

Tags:

reactjs

In the application I have to take the value from Input Value field and set the value from Input Value field to Set Value field. When Input Value changes onChange function is trigger and value is assigned to variable. The variable v is being used in Set Value field to set the value of the input.

Value isn't being set on Set Value field.

I have prepared a codesandbox.io to illustrate the issue I'm having.

export default function App() {
  let v = "0.00";

  function onChange(event) {
    v = event.target.value;
  }

  return (
    <div className="App">
      <label>Input Value</label>&nbsp;&nbsp;
      <input
        type="number"
        step="0.01"
        placeholder="0.00"
        onChange={(e) => onChange(e)}
      />
      <br />
      <br />
      <label>Set Value</label>&nbsp;&nbsp;
      <input value={v} type="number" step="0.01" placeholder="0.00" readOnly />
    </div>
  );
}
like image 586
Kestal Avatar asked Sep 06 '25 03:09

Kestal


1 Answers

You should call useState to update values on re-rendering

export default function App() {
  const [value, setValue] = useState("0.00") //call useState to re-render UI as well as get new values

  function onChange(event) {
    setValue(event.target.value) //update your value here
  }

  return (
    <div className="App">
      <label>Input Value</label>&nbsp;&nbsp;
      <input
        type="number"
        step="0.01"
        placeholder="0.00"
        onChange={onChange}
      />
      <br />
      <br />
      <label>Set Value</label>&nbsp;&nbsp;
      <input value={value} type="number" step="0.01" placeholder="0.00" readOnly />
    </div>
  );
}
like image 195
Nick Vu Avatar answered Sep 07 '25 19:09

Nick Vu