Home > Enterprise >  How to delete the parent div when the button inside of it is clicked?
How to delete the parent div when the button inside of it is clicked?

Time:03-28

I have a button,

<div
    key={index}
    className='flex items-center justify-between px-1 bg-accent-tm mr-2 mb-1 text-white-tm text-sm rounded-sm'
>
    <span className="pr-2">{tag}</span>
    <button>
        <XCircleIcon className="h-4" />
    </button>
</div>

Which looks like this,

I'm trying to remove the whole <div> element when the <button> element is clicked. How can I do that?

I added an event to the button like this,

<div
    key={index}
    className='flex items-center justify-between px-1 bg-accent-tm mr-2 mb-1 text-white-tm text-sm rounded-sm'
>
    <span className="pr-2">{tag}</span>
    <button onClick={handleRemoveClick}>
        <XCircleIcon className="h-4" />
    </button>
</div>

and passed the following handleRemoveClick function,

function handleRemoveClick(event: MouseEvent<HTMLButtonElement>) {
        const target = event.target as SVGPathElement
        const removingText = target.parentElement!.parentElement!.parentElement!.children.item(0)!.innerHTML
        setTags(prev => (prev?.filter(tag => tag !== removingText)))
}

But this only works when I click the white coloured parts of the button not red coloured parts of it. Then I looked around and found that the event.target changes depending on where I click on the button. Solution I came up with is to add an if else to figure out where I clicked.

So, is there a better way to do this?

CodePudding user response:

Here is a simple solution to hide the button on click

export default function App() {
  const [hideButton, setHideButton] = useState(false);

  return (
    <div className="App">
      {hideButton ? null : (
        <div
          key={index}
          className="flex items-center justify-between px-1 bg-accent-tm mr-2 mb-1 text-white-tm text-sm rounded-sm"
          onClick={() => setHideButton(true)}
        >
          <span className="pr-2" onClick={(e) => e.stopPropagation()}>{tag}</span>
          <button>
            <XCircleIcon className="h-4" />
          </button>
        </div>
      )}
    </div>
  );
}
  • Related