Home > Enterprise >  React editing input element that has a value
React editing input element that has a value

Time:03-13

i have this input:

  <input
    type="text"
    autoFocus
    value={post.body}
   />

i want the user to be able to edit the value, i tried to set contentEditable but it doesn't work

CodePudding user response:

<input type="text" autoFocus defaultValue={post.body}/>

In your code, you can not edit value. Because you set value, so set defaultValue.

CodePudding user response:

You have to set event listener on this input to capture what is changing.

Your data should be state variable defined as

const [value, setValue] = useState("");

in your case the default value can be post.body

const [value, setValue] = useState(post.body);

and then in the input component connect all together

 <input
    type="text"
    value={value}
    onChange={(event) => setValue(event.target.value)}
   />
  • Related