I'm new to React, how come I get [object Object] all the time?

Hi!

So recently I was studying React, on a website project. I don’t have the github files yet, as an error occurred, but here is my counter.jsx file:

import React, { Component } from "react";
import { throwStatement, thisTypeAnnotation } from "@babel/types";

class Counter extends Component {
  state = {
    count: 0
  };

handleIncrement = () => {
    this.setState({ count: this.state + 1 });
  };

render() {
    return (
      <div>
        <span className={this.getBadgeClasses()}>{this.formatCount()}</span>
        <button
          onClick={this.handleIncrement}
          className="btn btn-secondary btn-sm"
        >
          Increment
        </button>
</div>
    );
  }

getBadgeClasses() {
    let classes = "badge m-2 badge-";
    classes += this.state.count === 0 ? "warning" : "primary";
    return classes;
  }

  formatCount() {
    const { count } = this.state;
    return count === 0 ? "Zero" : count;
  }
}

export default Counter;

And my index.js file:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import "bootstrap/dist/css/bootstrap.css";
import Counter from "./components/counter";

ReactDOM.render(<Counter />, document.getElementById("root"));

serviceWorker.unregister();

So the problem is, whenever I click the Increment button, I always get:

Capture.PNG

How do I get rid of the [object Object]1?

Thank you,

  • Zoe K.

I’m on mobile so apologies for lack of formatting. You are incrementing the state object instead of increment the count property:

Your code: this.state + 1
Should be: this.state.count + 1

4 Likes

Thank you @badsyntax! It helped for me!!

2 Likes