How to make the input element controlled? #3848
-
Hi, Visually I can type anything. It doesn't stay at 50.
How can I make it controlled on preact ? It is controlled in react. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
|
Beta Was this translation helpful? Give feedback.
-
I over simplified my issue and it got misunderstood.
is not supposed to change the displayed value if I don't rerender. Preact is making the input component uncontrolled which is not specified in the preact documentation because it is probably a unwanted bug 💥 on preact part. If you don't know what I mean by uncontrolled components : https://preactjs.com/guide/v8/forms/#controlled--uncontrolled-components I can temporally use the DOM value (instead of the prop called "value") with useRef to do the work.
|
Beta Was this translation helpful? Give feedback.
-
( Disclaimer: I'm fairly new to Preact so I may not get the details right ) The v10 docs have an example on how to do controlled forms (you linked to v8):
Preact doesn't automatically keep the DOM in sync with component state (I guess from what you write that React does, at least for inputs?). In other words: It doesn't prevent the (DOM) input from changing value unless you add an event listener for user input, then change the component state in response, which will cause Preact to apply its state (back) to the DOM. If you want to prevent the input value from changing, you may need to force the re-render by incrementing a state value (as preact won't re-render unless the state value actually changes): // Incrementing `n` will change the state and cause re-render
// and (re-)set the input value to `50`
const [ n, setN ] = useState( 0 );
const rerender = () => setN( n + 1 );
const value = 50;
return <input onInput{ rerender } value={ value } />; Does that answer your question? |
Beta Was this translation helpful? Give feedback.
<input value={input} disabled />
would do as you are suggesting, typing does not override the value 😅