1

const App = () => {
  return (
    <div>
      <div
        onClick={() => {
          console.log("Inner div");
        }}
      >
        Inner div
      </div>
    </div>
  );
};

ReactDOM.render(
  <React.Fragment>
    <App />
    <div
      onClick={() => {
        console.log("Outer div");
      }}
    >
      Outer div
    </div>
  </React.Fragment>,
  document.getElementById("impact")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
    
    <div id="impact"></div>

I have a simple code written using react and built with Webpack 5. The problem is that click by "Inner div" doesn't work but click by "Outer div" works good. When I pass an inline template to ReactDom.render function, onClick works, but if I use a functional component, it doesn't. What can cause this behavior? Maybe the problem is with Webpack config?

You can use this repo to reproduce the problem: https://github.com/nikitabelotelov/react-click-bug-reproduce

KcH
  • 3,302
  • 3
  • 21
  • 46
  • Are you sure you have enough "hitting area" in your inner div to hit and trigger the onClick? just use a ` – Martin Sep 27 '21 at 07:44

2 Answers2

1

Find the same issue here: js events not firing in webpack built react application It also worked me. I removed index.bundle.js script from index.html file. Seems like it happens when you have duplicated scripts on your page.

0

Your React code looks fine to me. Here it is embedded in a script tag. It seems to work as you expect, so the problem is likely related to something in your build process.

<script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.15.7/babel.min.js"></script>

<div id="impact"></div>

<script type="text/babel" data-type="module" data-presets="env,react">

const App = () => {
  return (
    <div>
      <div
        onClick={() => {
          console.log("Inner div");
        }}
      >
        Inner div
      </div>
    </div>
  );
};

ReactDOM.render(
  <>
    <App />
    <div
      onClick={() => {
        console.log("Outer div");
      }}
    >
      Outer div
    </div>
  </>,
  document.getElementById("impact")
);

</script>
jsejcksn
  • 27,667
  • 4
  • 38
  • 62