0

I'm new in reactjs. I'm trying to add a onClick event in my child component like:

## BlogList.js
<button onClick={handleDelete(blog.id)}>delete</button>

the handleDelete function in the parent component is:

## Home.js
    const handleDelete = (id) => {
        const newBlogs = blogs.filter((blog) => blog.id !== id)
        setBlogs(newBlogs)
    }

The error message is: Cannot update a component (Home) while rendering a different component (BlogList). To locate the bad setState() call inside BlogList

Why didn't it work? Why did it have to write like <button onClick={()=>handleDelete(blog.id)}>delete</button> ?

1
  • 1
    You can pass it like onClick={handleDelete} in-case you don't want to pass any params. But if you want to pass in params inside the function you have to use that syntax onClick={()=>handleDelete(blog.id)}. On the first approach I mentioned you are simply passing in all the events associated with that button Commented Dec 17, 2022 at 4:27

1 Answer 1

2
<button onClick={handleDelete(blog.id)}>delete</button>

The above code means you execute the function right away after JSX renderings.

You can check the below code to understand immediate function execution

function handleDelete(id) {
  console.log('Executed handleDelete')
}

handleDelete() //executed immediately with `()`!

To avoid that case, you should remove () like below

function handleDelete(id) {
  console.log('Executed handleDelete')
}

handleDelete //nothing happens!

Similarly, in React, you can avoid that case by introduce a wrapper

function handleDelete(id) {
  console.log('Executed handleDelete')
}

const onClick = () => handleDelete(1)

And then call it's like below

//logic
function handleDelete(id) {
   console.log('Executed handleDelete')
}

const onClick = () => handleDelete(1)

...

//JSX

<button onClick={onClick}>delete</button>
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.