I'm setting the value of an input to a property on an object (from the state). I have an onChange
event to update the state. However, when I try to type, it doesn't actually update in the input. If I don't use an object and just have a string, it works fine. How can I fix this?
Demo of the issue
My code:
import React from "react";
export function App() {
const [data, setData] = React.useState({
test: "hello"
});
const change = (e) => {
data.test = e.target.value;
setData(data);
};
return <input value={data.test} onChange={change}></input>;
}
CodePudding user response:
Per the comment by Aman Sadhwani, I used spread syntax to update the state without modifying the original object.
const change = (e) => {
setData({
...data,
test: e.target.value
});
};
CodePudding user response:
Thanks, @Aman Sadhwani. Use Spread operator to update the state.
import React from "react";
export function App() {
const [data, setData] = React.useState({
test: "hello"
});
const change = (e) => {
setData({
...data
test:e.target.value
});
};
return <input value={data.test} onChange={change}></input>;
}