score:9

Accepted answer

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"),
    }),
...

score:-1

Did you import this in your file, if not then add this tine on top

import React from 'react';

score:0

Try typing your function as React.FC.

Create a typescript (tsx) file and use the upcoming code:

import React from "react";

export const MyButton: React.FC = () => {
  return (
    <button
      onClick={() => {
        console.log("test");
      }}
    >
      Button
    </button>
  );
};

Note that using this code, you are typing the component making sure that your function is typed as React.FunctionComponent.

score:1

Use named function instead of anonymous function. Named functions are very useful for identifying what functions caused errors during development as well as when retrieving logs from your users.

import React from "react";

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

It is a good practice to name-all-functions for a better developer debugging (and development) experience which anonymous function does not provide.

For more clarification between Named and Anonymous function Learn the benefits of Named vs Anonymous function here


Related Query

More Query from same tag