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
The below code illustrates how not to use onClick event handler. The
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
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
There are a few ways to handle onClick handlers that accept arguments.
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
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