Ad

OnClick Not Firing Within Map - ReactJS

- 1 answer

I've searched around and thought I had found a solution. However, my code just doesn't seem to fire the 'handleClick' function via onClick. At first I thought it was a scope issue, so I passed 'this' into the map which fixes the console error but the function never fires...

If I move the button outside of the map it works, no errors are being thrown.

    handleClick: function(event) {
       console.log('Clicked');
       this.setState({personName: 'Hello'});
    },

     render: function () {
       var text = this.state.personName;
       var parsedItems = this.state.userItems.map(this.prepareData);

    return (
        <div>
            <button onclick={this.handleClick}>Click me!</button>   <---- This works
            <div className="row hidden-xs">
                <div className="loading"></div>
                {
                    parsedItems.map(function (itemData, index) {
                        return (
                            <div key={itemData.itemCode}>
                                <p>{text}</p>
                                <p><button onclick={this.handleClick}>Click me!</button></p>  <-- This doesn't work
                            </div>
                        )
                    }, this)
                }
           )
    }
Ad

Answer

I'm not sure why the down voting but I did find a solution to this in the end. Just in case anyone else comes across this, the onclick is case sensitive so needs to be onClick this doesn't throw any errors which is annoying!

Ad
source: stackoverflow.com
Ad