Answer the question
In order to leave comments, you need to log in
How to correctly change the value in input using React?
Hey!
Confused about Controlled Components.
https://codesandbox.io/s/cranky-bogdan-cwyh0?file=...
There is a simple input1
and input2
in the form of a component
On change input1
, its value must be specified inside the field input2
On change input2
, its value is simply stored in state
The problem is that React says you need to use only defaultValue, and if it is forced to specify value={state}
, then it gives a component manageability error.
How is it correct to pass value from one input to another input ?
I don’t want to use ref, because the documentation says that this is the most extreme case.
ps In the documentationit is indicated about controlled components, but in the examples only the output of input.value in any other block, except for another input,
Answer the question
In order to leave comments, you need to log in
import { useEffect, useState } from "react";
export default function MyComponent() {
const [val1, setVal1] = useState();
const [val2, setVal2] = useState();
useEffect(() => setVal2(val1),[val1]);
return <>
<input type="text" value={val1} onChange={(ev) => setVal1(ev.target.value)} />
<input type="text" value={val2} onChange={(ev) => setVal2(ev.target.value)}/>
<div>{val2}</div>
</>
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question