I'm Newbie studying React student alone. Also, Sorry I'm not good English.
3 days ago, I want to change state to button's value when click button. So, I just simply coding like this.
/* SKIP CODE */
const [state, setState] = useState("");
/* SKIP CODE*/
<button onClick={setState("×pan=PT1H")}>1 hour</button>
/* SKIP CODE*/
But It's not work. So I Googling 3 days, finally I solve it like this.
<button onClick={() => {setState("×pan=PT1H")}}>1 hour</button>
but, I don't know why. Can you explain me soooooooooooo easily?
CodePudding user response:
React on render invokes the function call, hence it is used as variables and invoked on-demand for performance optimisation.
const callMe = () => {
console.log('i am called when the button was clicked not on render');
}
<Button onClick={callMe} />
CodePudding user response:
In
<button onClick={setState("×pan=PT1H")}>1 hour</button>
you are assigning to onClick
the result of setState("×pan=PT1H")
, so when the method onClick is dispatched by the button, it doesn't executes any function because it has assigned a value, not a function.
However, in <button onClick={() => {setState("×pan=PT1H")}}>1 hour</button>
you're assigning to onClick that function, so everytime the method onClick
is dispatched by the button it executes the function setState.
CodePudding user response:
onClick need a callback function, that you need to pass, In your case you are passing an arrow function as a callback, you can also pass a normal function to onClick event.
function onBtnClick(){
//do the action here.
}
<button onClick={onBtnClick}>Click Me!</button>
Or you can use an arrow function:
const onBtnClick = () => {
//do the action here.
}
<button onClick={onBtnClick}>Click Me!</button>
Or you can pass an arrow function inline.
<button onClick={() => { //do the action here }}>Click Me!</button>
if your function is returning a single line of code, as in your case, you don't need brackets:
<button onClick={() => setState("×pan=PT1H")}>1 hour</button>