0

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.
sanad qazi
  • 31
  • 5
  • I don't understand why I am getting white blank page – sanad qazi Mar 15 '22 at 12:01
  • So you're not even seeing the button "Increase Count"? – Ameer Mar 15 '22 at 12:03
  • I suspect the problem is not in the code you are showing. If you press F12 on most browsers while your app is showing a blank page you can check if the HTML elements are displaying at all, if they are hidden due to CSS setting the text white, etc. – haleonj Mar 15 '22 at 12:04
  • If you have a blank page then, presumably, the React application isn't running at all. You need to take a step back and debug from there. – Quentin Mar 15 '22 at 12:04
  • For testing I have included a button in `App.js` just below that's also not getting rendered on screen, but when I remove the ` ` from App.js then test button get rendered on screen which means React app is working. – sanad qazi Mar 15 '22 at 12:08
  • Any errors in console? – tomleb Mar 15 '22 at 12:13
  • @tomleb3 updated console log errors in question – sanad qazi Mar 15 '22 at 12:17
  • Does this anwers your question? [Set initlal react state](https://stackoverflow.com/questions/37782403/set-initial-react-component-state-in-constructor-or-componentwillmount) – 0stone0 Mar 15 '22 at 12:19

2 Answers2

2

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.

I'm Joe Too
  • 5,468
  • 1
  • 17
  • 29
-1

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 };
}
3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
  • 3
    No need for the parentheses... – tomleb Mar 15 '22 at 12:18
  • This is not what's causing the mentioned error at all. This would be an error aswell, but at the same time, this is a terrible way to handle state changes. [React docs](https://reactjs.org/docs/state-and-lifecycle.html#using-state-correctly), [more react docs](https://reactjs.org/docs/faq-state.html), [KCD state management](https://kentcdodds.com/blog/application-state-management-with-react) – Art Mar 15 '22 at 13:28
  • I see that the person who asks is just starting to learn programming. Before sending documentation and confusing a person in theory, please explain what was the mistake and show me the most correct way please. And then I can find links to the documentation myself. – Artashes Sargsyan Mar 15 '22 at 14:45
  • I just suggested what exactly the problem is and the question was not about coding style and the best practices. – Artashes Sargsyan Mar 15 '22 at 14:59
  • 2
    @Art The code in this answer was referring to state initialisation in the constructor. It isn't trying to change state, but initialises it. – 3limin4t0r Mar 15 '22 at 17:33
  • @3limin4t0r You're right, my apologies! – Art Mar 15 '22 at 17:59