React: onClick called on immediately after page load

Created on 17 May 2014  路  2Comments  路  Source: facebook/react

When I load my page the last onClick event in my module is triggered immediately. In the example below handleClick('/code') is executed. How can I fix this?

sidebar.js:

/**
 * Module dependencies
 */

var react = require('react');
var router = require('page');

/**
 * Component
 */

module.exports = react.createClass({
  displayName: 'sidebar',

  render: function() {
    return react.DOM.aside({className: 'sidebar'},
      react.DOM.ul({className: 'sidebar-index'},
        react.DOM.li(null, 'Guide'),
        react.DOM.ul(null,
          react.DOM.li(null, 
            react.DOM.a({href: '/ux', onClick: handleClick('/ux')}, 'UX')
          )
        ),
        react.DOM.ul(null,
          react.DOM.li(null, 
            react.DOM.a({href: '/visual', onClick: handleClick('/visual')}, 'Visual')
          )
        ),
        react.DOM.ul(null,
          react.DOM.li(null, 
            react.DOM.a({href: '/code', onClick: handleClick('/code')}, 'Code')
          )
        )        
      )
    )
  }
});

/**
 * Handle click
 *
 * @param {String} url
 * @api private
 */

function handleClick(url) {
  router(url);
}

Most helpful comment

(Without intending to come across as offensive)
You've misunderstood a basic principle in JavaScript, funcName(...) is _always_ an immediate function-call. I.e. onClick: handleClick('/ux') sets onClick to the return value of handleClick('/ux').

What you really want is onClick: handleClick.bind(null, '/ux'), the return value of bind is a new function, when called boundFunction(...) actually calls handleClick('/ux', ...).

Short: replace onClick: handleClick(...), with onClick: handleClick.bind(null, ...).

All 2 comments

(Without intending to come across as offensive)
You've misunderstood a basic principle in JavaScript, funcName(...) is _always_ an immediate function-call. I.e. onClick: handleClick('/ux') sets onClick to the return value of handleClick('/ux').

What you really want is onClick: handleClick.bind(null, '/ux'), the return value of bind is a new function, when called boundFunction(...) actually calls handleClick('/ux', ...).

Short: replace onClick: handleClick(...), with onClick: handleClick.bind(null, ...).

Haha, oh you're right. That was silly. Thanks!

Was this page helpful?
0 / 5 - 0 ratings