I am new to react, I made a simple component and render some data into this component but I don't see any output on the browser and I am getting this error on the console "react_dom_client__WEBPACK_IMPORTED_MODULE_1__.render is not a function".
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
// import App from './App';
// import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.css';
import Counter from './components/counter';
ReactDOM.render(<Counter />, document.getElementById("root"));
// registerServiceWorker();
counter.jsx
import React, {Component} from 'react';
class Counter extends Component {
state = {
count : 1,
}
render() {
return (
<div>
<span>{this.formatCount()}</span>
</div>
);
}
formatCount() {
const {count} = this.state;
return count === 0 ? 'Zero' : count;
}
}
export default Counter;
You need to create a root and then render with it:
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Counter />);
Few things are missing on your Counter class component, see below:
class Counter extends Component {
// You need to call the Component constructor so the class Counter inherit
// the React Component properties and methods
constructor(props) {
super(props);
// You need to add the state to 'this' so you can reference it later
this.state = {
count: 1
};
}
// Create the function before you call it, that is why I move
// it at the top of the render
formatCount() {
const {count} = this.state;
return count === 0 ? 'Zero' : count;
}
render() {
return (
<div>
<span>{this.formatCount()}</span>
</div>);
}
}
// This is fine as long as you have a div with id of root
ReactDOM.render(<Counter />, document.getElementById("root"));
Hope that helps
Try this:
import React from 'react'
import ReactDOM from 'react-dom/client'
import 'bootstrap/dist/css/bootstrap.css';
import Counter from './components/counter';
const root = ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<Counter />
</React.StrictMode>);
React.StrictMode is a tool for highlighting potential problems in an application, StrictMode does not render any visible UI. It activates additional checks and warnings for its descendants. see https://reactjs.org/docs/strict-mode.html for more information.