最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Active class in pagination in React - Stack Overflow

programmeradmin7浏览0评论

I've made a pagination, everything works, but I don't know how to set active class on single page.

This is my example:

Pagination code:

    const renderPagination = numbers.map(number => {
        return (
            <li className="controls" key={number} id={number} onClick={this.handlePages}>
                {number}
            </li>
        );
    });

Full example:

codepen

I've made a pagination, everything works, but I don't know how to set active class on single page.

This is my example:

Pagination code:

    const renderPagination = numbers.map(number => {
        return (
            <li className="controls" key={number} id={number} onClick={this.handlePages}>
                {number}
            </li>
        );
    });

Full example:

codepen

Share Improve this question edited May 31, 2018 at 14:22 Neil asked May 31, 2018 at 14:07 NeilNeil 151 silver badge4 bronze badges 3
  • Do you mean on the buttons of the page switching element? Like highlight the button "2" when on page 2? – Pierre C. Commented May 31, 2018 at 14:13
  • Yeah, that's what I mean. – Neil Commented May 31, 2018 at 14:16
  • @neil, you specifically got an error that you need to include your code in the post. Trying to circumvent that requirement by marking some random text as code isn't cool. Please insert your code to your post. – Chris Commented May 31, 2018 at 14:19
Add a ment  | 

2 Answers 2

Reset to default 6
<li className={(this.state.currentPage === number ? 'active ' : '') + 'controls'} key={number} id={number} onClick={this.handlePages}>
  {number}
</li>

You can add class when state equal number

https://codepen.io/titan_dl_1904/pen/XYbjye

Since the currentPage is in the state you can grab it from there and pare it to the number of the page link you are displaying

    const renderPagination = numbers.map(number => {
        var activeClass = this.state.currentPage === number ? 'active' : '';
        return (
            <li className={`controls ${activeClass}`} key={number} id={number} onClick={this.handlePages}>
                {number}
            </li>
        );
    });

Updated demo (with some styling too): https://codepen.io/gpetrioli/pen/MXwbYv

发布评论

评论列表(0)

  1. 暂无评论