'this.handleClick.bind(this) in function component

I want to create a pagination using a function component in React. My problem is that I can't use this.handleClick.bind(this) using this kind of structure. Is it possibile to use the pagination as well in other ways still using a function component? The code now is

import React from "react";

const Pagination = (props) => {
  this.handleClick = this.handleClick.bind(this); // I can't use it
  const pageNumbers = [];

  for (let i = 1; i <= Math.ceil(props.nameList.length / props.todosPerPage); i++) {
    pageNumbers.push(i);
  }
  const renderPageNumbers = pageNumbers.map((number) => {
    return (
      <li key={number} id={number} onClick={this.handleClick}>
        {number}
      </li>
    );
  });
  return <ul id="page-numbers">{renderPageNumbers}</ul>;
};

export default Pagination;


Solution 1:[1]

In functional component, you just have to define and use method directly without binding to context

import React from "react";

const Pagination = (props) => {
  const handleClick = (event) => {
    console.log('ok')
  }
  const pageNumbers = [];

  for (let i = 1; i <= Math.ceil(props.nameList.length / props.todosPerPage); i++) {
    pageNumbers.push(i);
  }
  const renderPageNumbers = pageNumbers.map((number) => {
    return (
      <li key={number} id={number} onClick={handleClick}>
        {number}
      </li>
    );
  });
  return <ul id="page-numbers">{renderPageNumbers}</ul>;
};

export default Pagination;

Solution 2:[2]

When you’re passing onClick handler you’re changing context from your component to a button element, meaning when your handler will be invoked this will refer to a button which in turn doesn’t have .setState method you will try to call. In order to fix it you basically have two options:

  1. Explicitly bind this inside method to your component

  2. Use class fields creating methods with arrow function:

class MyComponent extends React.Component {
  state = {
    name: 'Hello World'
  };

  handleClick = () => {
    this.setState({
      name: ' Welcome to React'
    });
  };

  render() { /* As usual */  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Arrow function does not have concept of this and this inside arrow function always refers to outer context at declaration time, which will always be your component (exactly what you need).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hgb123
Solution 2 Zach Jensz