I am trying to create a count function in which I want counter to get increased by 1 when user click on button, but code is getting compiled successfully and react app is showing white blank page.
App.js:
import './App.css';
import Count from './Components/Counter';
function App() {
return (
<div className='App'>
<Counter></Counter>
</div>
);
}
export default App;
Counter.js (inside src/Components Folder):
import React, {Component} from "react";
class Counter extends Component{
constructor(){
super();
this.state({
count:0
});
}
count(){
this.setState({
count : this.state.count + 1
}
);
}
render(){
return(
<div>
<h1>
{this.state.count}
</h1>
<button onClick={() => {this.count()}}>Increase Count</button>
</div>
);
}
}
export default Counter;
UPDATE:
Errors in console:
Uncaught TypeError: this.state is not a function
at new Counter (Counter.js:6:1)
at constructClassInstance (react-dom.development.js:12709:1)
at updateClassComponent (react-dom.development.js:17425:1)
at beginWork (react-dom.development.js:19073:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)
at beginWork$1 (react-dom.development.js:23964:1)
at performUnitOfWork (react-dom.development.js:22776:1)
at workLoopSync (react-dom.development.js:22707:1)
The above error occurred in the <Counter> component:
at Counter (http://localhost:3000/static/js/bundle.js:109:5)
at div
at App
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
The error tells you - this.state is not defined. You need to first define that in your class:
import React, { Component } from "react";
class Count extends Component {
state = {
count: 0
};
count() {
this.setState((prevState) => ({
...prevState,
count: (prevState.count += 1)
}));
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button
onClick={() => {
this.count();
}}
>
Increase Count
</button>
</div>
);
}
}
export default Count;
When it comes to things like incrementing values, also take note of how I changed setState. To protect against other things that may also change the state and throw your incrementer out of sync, you'll probably want to access the previous state just before changing it in the callback. This way, if something else changes the count before the state updates, it will make sure it has the latest counter when adding to it.
There is a TypeError this.state is not a function
constructor(){ super(); this.state({ count:0 }); }
Needs to be:
constructor(){
super();
this.state = { count: 0 };
}