Search code examples
reactjsnpmwebpackwebpack-dev-serveryarnpkg

React onClick not working in any of my browsers, but for colleagues it does


I've created an onClick handler in a very simple React function component:

export default function MyButton() {
   return (
      <button
         onClick={() => {
            console.log('test');
         }}
      >
         Button
      </button>
   );
}

Now the weird part: no matter what browser I use, the event is not firing. I've created such a component hundreds of times and everything was good, until now.

For everyone else this code works, as it was intended.

I cannot share the whole project or an example repository. It's really nothing but a simple React app you see everywhere.

What could be the reason for why it's not working on my system?

EDIT:

The error was somehow within yarn. I called webpack-dev-server -d source-map --mode=development for development and I am using "webpack-dev-server": "^4.0.0-beta.0". I think the cache could've gotten corrupted somehow.

To fix it, I removed my output directory and started the script with npm instead of yarn. This way it worked, even when I use yarn again.

I really don't know why this happened. Would be happy to know why.


Solution

  • I also faced the same issue and the reason of the issue (in my case , probably yours ) is HtmlWebpackPlugin, HtmlWebpack Plugin is adding a addition script tag of bundle in head tag of index.html.

    my html

    <html>
      <head>
        <title>my-react-app</title>
      </head>
      <body>
        <div id="root"></div>
      </body>
    </html>
    

    htmlwebpackplugin generated html

    <html>
      <head>
        <title>my-react-app</title>
      <script defer src="bundle.js"></script></head>
      <body>
        <div id="root"></div>
        <script src="bundle.js"></script>
      </body>
    </html>
    

    because of this additional script tag, there was a problem in react (i read a post on reddit regarding to this problem and he also have multiple script of same bundle and he was having the same problem), i solved it by deleting my script tag, but we can use copywebpack plugin to just copy html. Or other solution is to configure htmlwebpackplugin suck a way that it will not inject any addition tags

    ...
        new HtmlWebpackPlugin({
          name: "index.html",
          inject: false,
          template: path.resolve(__dirname, "public/index.html"),
        }),
    ...