Borislav Hadzhiev
Sat Apr 16 2022·2 min read
Photo by freestocks
onClick
listener to be a function error #The error "Expected onClick
listener to be a function" occurs when we pass a
value that is not a function to the onClick
prop of an element. To solve the
error, make sure to only pass functions to an element's onClick
prop.
Here is an example of how the error occurs.
const App = () => { // ⛔️ Warning: Expected `onClick` listener to be a function // instead got a value of `string` type. return ( <div> <button onClick="console.log('Click')">Click</button> </div> ); }; export default App;
We passed a string to the button's onClick
prop when a function is expected.
To solve the error, make sure to pass a function to the element's onClick
prop.
const App = () => { const handleClick = () => { console.log('button clicked'); }; return ( <div> <button onClick={handleClick}>Click</button> </div> ); }; export default App;
We passed a function to the element's onClick
prop which resolved the error.
However, notice that we aren't calling the function when passing it to the prop.
We are passing a reference to the function, not the result of calling the function.
A common thing you have to do is pass an argument to the event handler. You can do that by using an inline arrow function.
import {useState} from 'react'; const App = () => { const [count, setCount] = useState(0); const handleClick = (event, num) => { console.log(event.target); console.log('button clicked'); setCount(count + num); }; return ( <div> <h2>{count}</h2> <button onClick={event => handleClick(event, 100)}>Click</button> </div> ); }; export default App;
The handleClick
function is called with the event
object and a number
parameter.
Notice that we aren't passing the result of calling the handleClick
function
to the onClick
prop.
We are actually passing it a function that takes an event
object as a
parameter and returns the result of calling the handleClick
function with the
event
and the number 100
as arguments.
It is very important to not pass the result of calling the handleClick
function to the onClick
prop because then the function would get invoked
immediately as the page loads and that could cause an infinite re-render loop.