-6
import React from 'react'

const Buttons = React.createClass({

    getInitialState() {
         return {clicks: 0}
    },

    countClicks() {
        this.setState({
            clicks: ++this.state.clicks
        })
        console.log(this.state.clicks)
    }

    render() {
        return (
            <div>
                <div onClick={console.log("HEYYY")}>This should log "HEYYY"</div>
            <div onClick=({this.countClicks()}>This should update clicks</div>

        )
    }
})

This will print "HEYYY" and 1 respectively on the first render but never do anything when actually clicked.

While this gave me some headache I found the solution in an example:

//Instead of doing this
<a onClick={this._changeValue(2)}>Change Value</a>

//Do this
<a onClick={this._changeValue.bind(2)}>Change Value</a>

Ah, perfect, I thought. Except that when I try it I get an error:

TypeError: Cannot call method 'bind' of undefined

I removed the simple console.log because I have no idea what to bind in it and went with countClicks() only, and I did get it somewhat working when I removed the parenthesis like so:

<div onClick=({this.countClicks.bind(this)})>This should update clicks</div>

First of all, why can't I bind something when I have the parenthesis in? Second, I instead got an ugly WARNING:

Warning: bind(): You are binding a component method to the component. React does this for you automatically in a high-performance way, so you can safely remove this call.

Is React stupid?!

Or am I..?

Yeats
  • 2,112
  • 3
  • 30
  • 46
  • yeats @Andy_D hit the nail on the head. if you pass a function to the click handler then it wont invoke it. `()` parenthesis invoke the function. so removing them and just saying `onClick={this.countClicks}` is how you are supposed to do it. and there is a TON of documentation on that – John Ruddell Jun 09 '16 at 07:02
  • onClick is not just a react thing. its a html attribute that has been around for a long time. it functions just like that attribute. http://stackoverflow.com/questions/18680248/html-button-onclick-event ... to invoke the function you let the click handler do it. the click handler will call the function when you click it. so theres no need for parenthesis. the parenthesis execute the function and the onclick handler cannot execute a called function – John Ruddell Jun 09 '16 at 07:37

1 Answers1

-5

My own solution:

render() {
    const self = this

    <div onClick={function() { self.countClicks() }}>This should update clicks</div>
}

No use of bind, no errors, no warnings.

Yeats
  • 2,112
  • 3
  • 30
  • 46