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>
<input
type="number"
step="0.01"
placeholder="0.00"
onChange={(e) => onChange(e)}
/>
<br />
<br />
<label>Set Value</label>
<input value={v} type="number" step="0.01" placeholder="0.00" readOnly />
</div>
);
}
CodePudding user response:
When you want to track data in a React component that persists between renders, you need to use state (or a ref, or other patterns, but state works best for your situation).
The new React beta Docs have a fantastic section on managing state: https://beta.reactjs.org/learn/reacting-to-input-with-state
You'll want to do something like:
export default function App() {
const [v, setV] = useState(undefined);
return (
<div className="App">
<label>Input Value</label>
<input
type="number"
step="0.01"
placeholder="0.00"
onChange={(e) => setV(e.target.value)}
/>
<br />
<br />
<label>Set Value</label>
<input value={v} type="number" step="0.01" placeholder="0.00" readOnly />
</div>
);
}
CodePudding user response:
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>
<input
type="number"
step="0.01"
placeholder="0.00"
onChange={onChange}
/>
<br />
<br />
<label>Set Value</label>
<input value={value} type="number" step="0.01" placeholder="0.00" readOnly />
</div>
);
}