The onClick property accepts a function as an argument. Therefore, you should pass a reference to a function or an anonymous function to the onClick property. Passing someFunctionName()
is not a function or a reference to a function. It is a function call, meaning you are executing the someFunctionName
function inside the onClick
argument. That's the reason why your function passed to onClick event is executed immediately on page render.
The below code illustrates how not to use onClick event handler. The handleOnClick
function is executed immediately after the page is rendered.
export const App = () => {
const handleOnClick = () => {
alert("This message displays on page render")
}
return(
<>
<div>React js onClick</div>
<div><input type="text" value="" onClick={handleOnClick()}/></div>
</>
)
}
export default App
How to pass a function reference to onClick?
Just pass the function name to the onClick event. Do not do a function call.
export const App = () => {
const handleOnClick = () => {
alert("This message is triggered by onClick")
}
return(
<>
<div>React js onClick</div>
<div><input type="text" value="" onClick={handleOnClick}/></div>
</>
)
}
export default App
What if I have to pass arguments to the onClick function?
There are a few ways to handle onClick handlers that accept arguments.
- Use an anonymous function in the onClick to pass the handler function with arguments
- Do a function call in the onClick handler and make the handler function return a function
Using anonymous function in onClick event
This is the simpler way to handle onClick event handlers with arguments.
import { useEffect } from "react"
export const App = () => {
const handleOnClick = (val: EventTarget) => {
console.log((val as HTMLInputElement).value)
}
return(
<>
<div>React js onClick</div>
<div><input type="text" onClick={(e) => handleOnClick(e.target)}/></div>
</>
)
}
export default App
Using a handler function that returns a function
In this method, we do a function call in the onClick event, and the function returns another function. The returned function is the handler function for the onClick event.
import { useEffect } from "react"
export const App = () => {
const handleOnClick = (name: string, website: string) => {
return () => {
console.log(name, website)
}
}<
return(
<>
<div>React js onClick</div>
<div><input type="button" value="Info" onClick={handleOnClick("LearnBestCoding", "learnbestcoding.com")}/></div>
</>
)
}
export default App