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);
}
(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!
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')setsonClickto the return value ofhandleClick('/ux').What you really want is
onClick: handleClick.bind(null, '/ux'), the return value ofbindis a new function, when calledboundFunction(...)actually callshandleClick('/ux', ...).Short: replace
onClick: handleClick(...), withonClick: handleClick.bind(null, ...).