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

can not add a onClick event in reactjs

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

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

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

>Solution :

<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>
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