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
CodePudding user response:
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/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/[email protected]/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>
CodePudding user response:
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.