lky
lky

Reputation: 1129

React JS - Expected `onClick` listener to be a function, instead got a value of `string` type

I'm struggling to understand why my onClick function is returning me an error? The functionality is working as expected but throws the following console error:

Expected onClick listener to be a function, instead got a value of string type.

{Object.keys(classGroups).map((key, index) => {
                return (
                    <div key={index}>
                        <span onClick={selectClassGroup(serving_point_id, key)}
                              className="block p-10 px-14 bg-theme-orange rounded text-white text-3xl text-center font-wicked">
                            {classGroups[key]}
                        </span>
                    </div>
                )})
            }

Here is my callback funtion:

const selectClassGroup = useCallback(
    (appId, key) => () => {
        window.location.replace('/#/serving-point/' + appId + '/' + key);
    },
    [],
)

What I am doing wrong for the error to appear?

Upvotes: 1

Views: 4902

Answers (1)

Amr
Amr

Reputation: 751

Problem

This is a normal function call , which calls the method as soon the rendering of the component happens.

 <span onClick={selectClassGroup(serving_point_id, key)}

Solution

use the arrow function to trigger the function only when onClick handler of the button is triggered.

 <span onClick={()=>selectClassGroup(serving_point_id, key)}

()=>{} is important to tell your onClick event that it is a function.

Upvotes: 4

Related Questions