1

I'm trying to build a class that's somehow modelled to how React classes are made. This is what I have so far:

export default class Pagination {
  constructor(attr) {
    const { totalPages } = attr;

    this.totalPages = totalPages;
    this.activePage = 1;
  }

  goToPage(newPageNumber) {
    console.log(newPageNumber);
  }

  render() {
    const pages = [];
    for (let i = 1; i <= this.totalPages; i++) {
      pages.push(`
        <li>
          <a href="javascript:void(0)" onclick="this.goToPage(${i})" class="${
        i === this.activePage ? 'active' : ''
      }">${i}</a>
        </li>
      `);
    }

    return pages.join('');
  }
}

The problem is, when I click a link, it says this.goToPage is not a function. How do I properly assign my class' method goToPage to the <a> tag?

1 Answer 1

2

You have to bind goToPage to the parent context:

constructor(attr) {
   const { totalPages } = attr;

   this.totalPages = totalPages;
   this.activePage = 1;

   this.goToPage = this.goToPage.bind(this);
}

However, keep in mind that calling onclick in an html element automatically assigns this to the elements context. So you'll need to utilize an eventListenter instead.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi, thanks for helping. I just tried doing that and I get this error: this.goToPage is not a function
@JudeMaranga Right. I see what you're doing now. in your case this refers to the html element. You'll need to attach an event listener, and call a method when the event is triggered, rather than using the html onclick property.
when would be the best time to set the event listener to each of the <a>'s? So like I'll create another class method called setEventListeners and then after calling render, I'll call that method?
Well, in React I would set the event listeners in componentDidMount(). So I suppose you should try to come up with some kind of logical equivalent to componentDidMount

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.