'How fix input and state in react?
Have
const [grade, setGrade] = useState({grade: null,})
const changeHandler = (event) => {if (event.value) {setGrade({ ...grade, [event.name]: event.value })} else {setGrade({ ...grade, [event.target.name]: event.target.value })}}
and input
<input
type="text"
name="grade"
className="homework-block-main-input"
onClick={changeHandler}
/>
when i print value in input i have
print "1" have "" print "12" have "1" print "123" have "12"
How to fix that?
when i print value in input i have
print "1" have "" print "12" have "1" print "123" have "12"
How to fix that?
Solution 1:[1]
First thing to point out is that if (event.value) {} doesn't make sense because event.value doesn't exists in event so it's always undefined, second thing, you should use onChange instead of onClick, the onClick event is generally used in buttons, third thing, you should do a console.log inside a useEffect to track the state correctly, here how you code should looks like:
const [grade, setGrade] = useState({ grade: '' });
const changeHandler = (event) => {
setGrade({ grade: event.target.value });
};
useEffect(() => {
console.log(grade)
}, [grade]);
return (
<input
type="text"
name="grade"
className="homework-block-main-input"
onChange={changeHandler}
></input>
);
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
