'Event handling is not working in a fresh react project

I've been trying my first steps with react.js and after playing around a bit (installing Bootstrap, adding some loaders for LESS & Co.) at some point the event handlers (onSubmit, onChange) stopped working. At first, I thought I just messed up my code.

However, when I copy the example for a controlled components form into a freshly initialized npm project with React 17.0.2, these handlers are still not working as expected. E.g. the onSubmit handler:

handleSubmit(event) {
  alert('A name was submitted: ' + this.state.value);
  event.preventDefault();
}

Neither does the alert show, nor is the default event handling prevented. The page simply reloads when I hit the submit button. For example, if I put an alert into the constructor it is being shown.

Here is the full package.json

{
  "name": "app-retry",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack",
    "start": "webpack-dev-server --open",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  },
  "devDependencies": {
    "@babel/core": "^7.16.12",
    "@babel/preset-env": "^7.16.11",
    "@babel/preset-react": "^7.16.7",
    "babel-loader": "^8.2.3",
    "html-webpack-plugin": "^5.5.0",
    "webpack": "^5.67.0",
    "webpack-cli": "^4.9.2",
    "webpack-dev-server": "^4.7.3"
  }
}

and here is the full webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: path.resolve(__dirname, 'src', 'index.js'),
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  dev: {
    hot: true,
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          // attach the presets to the loader (most projects use .babelrc file instead)
          presets: ["@babel/preset-env", "@babel/preset-react"]
        }
      }
    ]
  },
  plugins: [new HtmlWebpackPlugin({ template: path.resolve(__dirname, 'src', 'index.html') })]
};

The index.js is

import React from "react";
import ReactDOM from "react-dom";

// lines as copied from the react example

ReactDOM.render(
  <NameForm />,
  document.getElementById('root')
);

and finally the index.html template

<html>
  <head>
    <title>Hello world App</title>
  </head>
  <body>
  <div id="root"></div>
  <script src="./bundle.js"></script>
  </body>
</html>

What am I doing wrong? Is the example code wrong or is there a flaw in my setup?



Sources

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

Source: Stack Overflow

Solution Source