Home > Enterprise >  Why I cant get index from map to function?
Why I cant get index from map to function?

Time:05-20

Click handler:

 const deleteHandler = (e: React.MouseEvent<HTMLDivElement>, i: number) => {
        e.preventDefault()
        dispatch(deleteOffer(i)) //undefined
    }

Usage into React Component

  {offers.map((o, i) => (
                <div key={i} className={classes['OffersList__item']}>
                    <UIButton type={'primary'} onClick={(e:React.MouseEvent<HTMLDivElement>, i: number) => deleteHandler(e, i)}>
                        <FaTrash/>
                    </UIButton>
                </div>
            ))}

Why am I getting 'undefined' ?

CodePudding user response:

Instead of

onClick={(e:React.MouseEvent<HTMLDivElement>, i: number) => deleteHandler(e, i)}

Do

onClick={(e:React.MouseEvent<HTMLDivElement>) => deleteHandler(e, i)}

i doesn't exist in onClick mouse event, and this is also overriding your original index. That is also why typescript asked you to type the i's type otherwise i would have been inferred already.

  • Related