Expected onClick listener to be a function, instead got type object - react redux

Viewed 92618

As explained in the title, I am getting the error Expected onClick listener to be a function, instead got type object

But I am unable to understand why this isnt working. as far as I know, the onClick listener IS a function.

Here's, the CharacterList Component where the error comes from

import React,{Component} from 'react';
import {connect} from 'react-redux';
import {addCharacterById} from '../actions';
import {bindActionCreators} from 'redux';


class CharacterList extends Component{

    render(){
        //console.log('name : ',this.props.characters[2].name);
        return(
            <div>
            <h3>Characters</h3>
        <ul>
        {this.props.characters.map((character)=>{
            return(<li key={character.id}>{character.name}
                <div
                onClick={this.props.addCharacterById(character.id)}
                >+</div>
                </li>);
        })}
        </ul>
            </div>

            )
    }
}

function mapStateToProps(state){
    return {
        characters:state
    }
}




export default connect(mapStateToProps,{addCharacterById})(CharacterList);

And here's the action creator

export const ADD_CHARACTER='ADD_CHARACTER';
export function addCharacterById(id){
    var action ={
        type:ADD_CHARACTER,
            id
        }
        return action;

}

So, what do you guys think? what is the problem here?

5 Answers

Don't directly call functions in onClick event. It will recursively call the method. So make the onClick input as a callback method.

Change this line

onClick={this.props.addCharacterById(character.id)}

to

onClick={() => this.props.addCharacterById(character.id)}

Just an additional answer, make sure that all the onClick on your code has this kind of format.

onClick={() => this.props.addCharacterById(character.id)}

Even if one onClick has a format like this onClick={this.props.addCharacterById(character.id)} it can be problematic

Related