Home > OS >  can not add a onClick event in reactjs
can not add a onClick event in reactjs

Time:12-17

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

CodePudding user response:

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