'Button outside SVG not clickable

I have inside a button an animated SVG with some javascript, both have to be clickable BCS. of the animation and the state of the button itself which I need to handle.

can somebody help me

here you can see the full code in codesandbox https://codesandbox.io/s/vigilant-field-uyvvcr?file=/src/App.js

  const [activeFilter, setActiveFilter] = useState(false)

  const mouseEnter = () => {
    if (!activeFilter) {
      setActiveFilter(true)
    } else {
      setActiveFilter(false)
    }
    console.log(document.querySelector('object'))
  }

  return(
    <div className='search__container'>
      <div className='search'>
        <input placeholder='Search' type='text' />
        <button onClick={mouseEnter} className={`${activeFilter? 'active ' : ''}filterButton`}>
          <object type="image/svg+xml" data={FilterIcon} />
        </button>
      </div>
    </div>
  )
}


Solution 1:[1]

Why does this happen?

The html object element creates a new browsing context (you can see if you inspect with the developer tools: notice an embedded #document under object). The click event captured within the svg fires and bubbles up this context, but never goes beyond it. As a consequence, it never reaches the button element.

How to solve?

You don't want to have two browsing contexts. In order to do so, you can simply get rid of the object and insert the svg as a direct child of the button.

For your particular case of using react

You could use svg as react component:

<button onClick={mouseEnter} className={`${activeFilter? 'active ' : ''}filterButton`}>
  <FilterIcon />
</button>

You may want to investigate SVGR.

Hopefully, as it seems you are using create-react-app, it should come for free.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vincent