0

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;
1
  • 1
    <button onClick={e => handleDelete(book.id)}>delete</button> Commented Jun 23, 2022 at 18:28

1 Answer 1

1

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)        
};
Sign up to request clarification or add additional context in comments.

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.