Help
cancel
Showing results for 
Search instead for 
Did you mean: 
Pilot Lvl 2
Message 1 of 3

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

Solved! Go to Solution.

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.

2 Replies
Solution
Copilot Lvl 3
Message 2 of 3

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

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
Pilot Lvl 2
Message 3 of 3

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

Thank you @badsyntax! It helped for me!!