formsreact-hookspreactfreshjs

How to useState on a form input with predefined value?


I want to have a form with a default value, and whatever value users input will be caught. Here is my code:

import { useState } from "preact/hooks";

export default function test() {
  const [field1Value, setInput] = useState("");
  return (
    <div class="gap-2 w-full">
      <input
        value = 'Default value'
        onInput={(event) => setInput(event.target.value)}
      />
      {field1Value} 
    </div>
  );
}

If the form only has value and not onInput, or vice versa, then it works as expected. But if both of them appear, then users can't change it. It looks like this:

Why does this happen?


Solution

  • You are setting the value of the input to a hardcoded value value = 'Default value' You need to set it to the field value value={field1Value} and then set the predefined value in the input state

     const [field1Value, setInput] = useState("Default Value");
    
    import { useState } from "preact/hooks";
    
    export default function test() {
      const [field1Value, setInput] = useState("Default Value");
      return (
        <div class="gap-2 w-full">
           <input
            value={field1Value}
            placeholder="Enter value"
            onInput={(event) => setInput(event.target.value)}
          />
          {field1Value} 
        </div>
      );
    }