Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)        
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading