M
M
Mesuti2022-01-09 15:45:18
React
Mesuti, 2022-01-09 15:45:18

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 input1and input2in 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

1 answer(s)
G
gsaw, 2022-01-09
@Mesuti

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 question

Ask a Question

731 491 924 answers to any question