How to pass the array index value from array mapping to onClick function in React?

How do I pass the book.id value from the array mapping to the onClick function?

import { bookData } from './data';

const App = () => {
    const [state, setState] = useState(bookData)

    const handleDelete = (bookId) => {
        return (
            console.log(bookId)
        )
    };

    return
        <div className='bookCards'>
        {state.map((book) => {
            return (
                <div className='bookCard' key={book.id}>
                    <img className='coverImg' src={ book.coverimg } ></img>
                    <div>Title: { book.title }</div>
                    <div>Author: { book.author }</div>
                    <div>Year: { book.year_written }</div>
                    <div>Edition: { book.edition }</div>
                    <button onClick={handleDelete({ book.id })}>delete</button>                        
                </div>
            )
        })}
        </div>
export default App;

>Solution :

You need to call it and pass the id to it like so:

<button onClick={e => handleDelete(book.id)}>delete</button>

Related documentation: Passing Arguments to Event Handlers

And also change the body of the handleDelete to just console.log(bookId) if you like to see the passed id printed on console.

const handleDelete = (bookId) => {
    console.log(bookId)        
};

Leave a Reply