onClick not working React js

Note: Not a reactjs Expert :)

I am exploring reactjs right now and as of version 16.3.1 the arrow function worked for me

<button
    onClick={() => { console.log("button clicked");}}>
    button  
</button>

This is somewhat a noob sugesstion but please check the spelling of your onClick() function, I had spelt it wrong like onclick() and It took me a good hour to find it out.


You should set a function to onClick attribute, not call it. Should be: onClick={this.btnTapped} instead of onClick={btnTapped()}.

Also, it is possible to do like this:

<div 
  onClick={function(e) {
    this.btnTapped(); //can pass arguments this.btnTapped(foo, bar);          
  }}
 >

It's usually used when you need to pass an argument to your function.

Also, to be able to get component's context from the external function, you should use bind(this) method. Like: onClick={btnTapped.bind(this)}

And since you are using a scope function for mapping array, new context is created inside of: this.props.stations.map(function(station, index){}. And this is overridden. Just use an arrow function instead:

var stationComponents = this.props.stations.map((station, index) => {

   return <div onClick={this.btnTapped}><img src="img/test.png" />{station}</div>;

});

If your build system has support for babel, Use ES6 arrow functions in your react code.

If you are using ES6 class for creating components, use method binding at the constructor level to avoid binding at every render call and also provide a key to the div tag inside the map function.

class Test extends React.Component {
    constructor(props) {
        super(props);
        this.btnTapped = this
            .btnTapped
            .bind(this);
    }
    btnTapped() {
        console.log('tapped');
    }
    render() {

        return (
            <div>
                {this
                    .props
                    .stations
                    .map((station, index) => {
                        return <div key={index} onClick={this.btnTapped}>{station}</div>
                    })
                }
            </div>
        )
    }
}

var cards = ["amazon", "aeo", "aerie", "barnes", "bloomingdales", "bbw", "bestbuy", "regal", "cvs", "ebay", "gyft", "itunes", "jcp", "panera", "staples", "walmart", "target", "sephora", "walgreens", "starbucks"];

    
ReactDOM.render(
    <Test stations={cards}/>, document.getElementById('test-div'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<body>
  <div id="test-div"></div>
</body>