Asked By: Anonymous
I have the following reactJs component:
var Pagination = React.createClass({
// Basic pagination
render: function() {
// Do we have more then one page?
if (this.props.maxPages > 0){
var pageLink = this.props.maxPages;
var liElements = []
for (var i = 1; i <= pageLink; i++) {
liElements.push(<li key={i} id={i}><a href="#" onClick={this.props.handlePaginate(i)}>{i}</a></li>);
}
return (<ul className="pagination">{liElements}</ul>);
}else{
// Return nothing.
return ( <div></div> );
}
}
});
Each of the li
elements has a link element, and each of those has a onClick=...
attribute. the function thats being passed in is in a backbone view and has a console.log(id) in it. When the page loads, if there are two li
‘s on the page you get the i
variable spit out twice. This also happens if you click on one of the li
elements.
My question is – why is the onClick firing when I load the page for x number of li
elements and why, when I click on one li
element does it spit out the i
variable for each li
element?
the handlePaginate
function looks like
handlePaginate: function(id) {
console.log(id); //=> 1,2 (for two li elements with id's of 1 and 2)
return false; //=> doesn't actually stop the page from refreshing oO
}
Solution
Answered By: Anonymous
Turns out that the way to solve this is to do:
onClick = {this.props.handlePaginate.bind(this, i)}
in the link value, this will stop the pagination event from firing, and stop the page from refreshing when you click on a li
element.