[Edit]
+
0
-
0

React - different ways to handle input values change

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
import React, {useState} from 'react'; const App = () => { const [data, setData] = useState({}); const handleChange = (e) => { const target = e.target; setData(state => { return { ...data, [target.name]: target.value }; }); }; const handleSubmit = (e) => { e.preventDefault(); console.log(JSON.stringify(data, null, 4)); }; return ( <form onSubmit={handleSubmit}> <label><span>Field 1:</span><input name="field1" defaultValue={data.field1} onInput={handleChange} /></label><br /> <label><span>Field 2:</span><input name="field2" defaultValue={data.field2} onChange={handleChange} /></label><br /> <label><span>Field 3:</span><input name="field3" defaultValue={data.field3} onBlur={handleChange} /></label><br /> {/* Where: onInput calls handleChange function always on when data is input (works similar to onChange) onChange calls handleChange function always on when data is changed (called multiple times during value changing) onBlur calls handleChange function always on when input lost focus */} <button type="submit">Submit</button> </form> ); }; export default App;
Reset