Solve - Expected `onClick` listener to be a function error

avatar

Borislav Hadzhiev

Sat Apr 16 20222 min read

banner

Photo by freestocks

Solve - Expected 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.

expected onclick listener to be function

Here is an example of how the error occurs.

App.js
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.

App.js
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.

If you pass the result of calling the function, then the event handler would get invoked immediately when the page loads, which is not what we want.

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.

App.js
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.

onclick listener function

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.