Lee Loftiss
Lee Loftiss

Reputation: 3195

How to set parameter for onClick event

I am building a page selector for search results. I am using the following code to build the elements:

numbers.map(item=>{
                    counter ++
                    return(
                        <div className={'number-holder'} key={counter} onClick={() => changePage({counter})}>{counter}</div>
                    )
                }) 

The issue is this part:

changePage({counter})

It always returns the last value of the COUNTER variable, no matter which item it is. So, if there are 10 pages, and I click '5', it still returns '10'.

The use of COUNTER for the key and text between the DIV works, but for the function, it only returns the last value of COUNTER.

How an I change this so the changePage() function returns the correct number?

Upvotes: 1

Views: 54

Answers (2)

Mohammed Al-Reai
Mohammed Al-Reai

Reputation: 2786

you can add a property in the item from index look

numbers.map(item => {
    return (
        <div className={'number-holder'} key={item.id} onClick={() => changePage({counter: item.id+ 1})}>{index + 1}</div>
    )
})

or can ued the secand parameter in map for index element

numbers.map((item,index) => {
        return (
            <div className={'number-holder'} key={index} onClick={() => changePage({counter: item.id+ 1})}>{index + 1}</div>
        )
    })

i perfare to used the the first option tell me in commit if it work or not

Upvotes: 0

MaartenDev
MaartenDev

Reputation: 5802

The index of the map method can be used to get the correct offset:

numbers.map((item, index) => {
    return (
        <div className={'number-holder'} key={index} onClick={() => changePage({counter: index})}>{index}</div>
    )
})

You could also add +1 to show it as normal numbers:

numbers.map((item, index) => {
    return (
        <div className={'number-holder'} key={index} onClick={() => changePage({counter: index + 1})}>{index + 1}</div>
    )
})

Please note that using the index as key is not recommended, is it preferred to use an id of the object such as item.id. Read more about it here: https://reactjs.org/docs/lists-and-keys.html#keys

Upvotes: 2

Related Questions