0

I use glyphicon with delete function as below:

<i className="glyphicon glyphicon-trash" onClick={this.deleteBook(book._id)}></i>

I think it should delete when click but when the page render, all contents are deleted without clicking.

The following is all part of code:

<div className="container">
                <div className="row">
                    <div className="col-md-6">
                        <ul className="book-list">
                            {this.state.pageOfItems.map(book => (
                                <li key={book._id} className="book-list__item">
                                    <div className="book thumbnail">
                                        <div className="caption">
                                            <h3 onClick={() => this.props.history.push(`${this.props.match.url}/view/${book._id}`)}>{book.title}</h3>
                                            <h4>{book.bookdate}</h4>
                                            <i className="glyphicon glyphicon-trash" onClick={this.deleteBook(book._id)}></i>
                                        </div>
                                    </div>
                                </li>
                            ))}
                        </ul>
                    </div>
                    <div className="col-md-6">

                    </div>
                </div>
            </div>

3 Answers 3

3

Yes, inside JSX {...} all JS expression gets executed. So when you write, onClick={this.deleteBook(book._id)}, you are executing the function with this (), as you wrote this.deleteBook(book._id). Let's wrap it inside the Arrow fucntion as

onClick={() => this.deleteBook(book._id)}

With this onClick props, you attached a function object as an event handler. So when the click will happen this handler function will be called internally. Don't execute the event handler by yourself, let them called by the specific events you attached to.

Sign up to request clarification or add additional context in comments.

Comments

1

Either do this

onClick={() => this.deleteBook(book._id)}

Or second approach

onClick={this.deleteBook(book._id)}

Then where you define your function do this

this.deleteBook = id => () => {}

3 Comments

The second approach would call the function on render itself
No it will not this this.deleteBook = id => () => {} is same as this approach () => this.deleteBook(book._id)
@Adeel Imran, Thank you very much
1

Please using the onClick function as below:

onClick={() => this.deleteBook.bind(this, book._id)}

So for receiving book._id argument value after clicking on the element, use the following model:

deleteBook(id, event) {// todo someting}

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.