0

I have the following ReactJS code which I am using to render a number of buttons which will allow the user to navigate around the data returned from an API (a bunch of paginated images).

I have the multiple buttons displaying but they send i as 19 (the end value in the loop) to the handlePageClick() function.

How can I get the value of i to be passed to my handlePageClick() function?

handlePageClick( button ) {

    console.log( button );

    this.setState( prevState => {
        return {
            currentPage: button
        }
    }, () => {
        this.loadMedia();
    });

}

render() {

    // figure out number of pages

    const mediaButtonsNeeded = parseInt( this.state.totalMedia / this.state.perPage )

    var mediaButtons = [];
    for (var i = 0; i < mediaButtonsNeeded; i++) {
        mediaButtons.push(<button  onClick={() => this.handlePageClick(i)}>{i}</button>);
    }


    return (

        <div>

            <div>
                <h1>Media test</h1>
                {media}
                {mediaButtons}
            </div>

        </div>

    )

2 Answers 2

2

Since var is global scope variable declaration, your loop always rewrite i to next value.

Easiest solution is just replacing from var to let.

 for (let i = 0; i < mediaButtonsNeeded; i++) {// your code...
Sign up to request clarification or add additional context in comments.

Comments

0

This should work:

for (var i = 0; i < mediaButtonsNeeded; i++) {
        mediaButtons.push(<button  onClick={() => this.handlePageClick(i+"")}>{i}</button>);
}

Comments

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.