Update: Changing the @babel/preset-react
runtime to "automatic"
in the webpack.config.js
fixed it. The runtime defaults to "classic"
which I have to assume prevents the use of non-legacy react within my setup. I have partially confirmed this by successfully running the npm run build
command with the automatic runtime and the functional component.
webpack.config.js
presets: [
[
"@babel/preset-react",
{
runtime: "automatic",
},
],
"@babel/preset-env",
];
Still interested in anybody's explanation for this behavior!
I am using the webpack-dev-server and babel-preset-react. After changing the component to a functional one, it is no longer registered in the DOM. Further, it won't be rendered even though webpack is compiling successfully. Can anyone help me figure out why that happens and how I can fix it? Thank you!
I would like to use the functional component. Here's my code:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
index.js (with functional component)
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './components/App';
const container = document.getElementById('root');
const root = createRoot(container);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
App.js
export default function App() {
return (
<>
<h1>
Hello, World!
</h1>
</>
);
}
webpack.config.js
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.join(__dirname, '/dist'),
filename: 'bundle.js'
},
plugins: [
new HTMLWebpackPlugin({
template: './src/index.html'
})
],
module: {
rules: [
{
test: /.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-react', '@babel/preset-env']
}
}
}
]
}
}
Below is the initial component which I tried changing from being a class component to a functional component including the necessary changes from ReactDOM.render()
to createRoot()
. After that, the hot reloading webpack-dev-server was no longer able to render the <App />
component.
index.js (with class component)
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<>
<h1>
Hello World!
</h1>
</>
)
}
}
export default App;