hello i am wondering why only normal functions like below works and arrow functions do not.
const Form = () =>{
const [text, setText] = useState("");
const handle=(e)=>{
setText(e.target.value);
}
const alertText = (e) =>{
console.log(text);
alert(text);
}
return(
<>
<input onChange={handle}></input>
<button onClick={alertText}>submit</button>
<h1>{text}</h1>
</>
)}
using arrow functions like <input onChange={()=>handle}>
doesn't work at all and I have no idea what the difference between of them.
Well, that's because if you use an arrow function on the element you have to call it like this:
<input onChange={(e)=>handle(e)}>
component expects onChange as a function, that function will be called when the user changes the value of the input.
NOTE: It's syntactically correct but the handle function will not execute.
When you do
<input onChange={handle}></input>
// it's equivalent to
<input onChange={(e)=>{ setText(e.target.value); }}></input>
But when you do
<input onChange={()=>handle}></input>
// it's equivalent to
<input onChange={(e) => ()=>{ setText(e.target.value);}}></input>
You can do:
<input onChange={(e)=>handle(e)}>
You are not passing the event into the handle function