-1

This is a Reactjs code. Here i am trying to iterate and printing the Object data. But, facing an error --> TypeError: Cannot read properties of undefined (reading 'state'). I want to know what i am doing wrong here.

import React, { Component } from 'react'

class App extends Component {

  state = {
    posts: {
      ASlot: true,
      BSlot: true,
      CLive: true,
      DRedirect: true
    }
  }

  Club() {
  for(const property in this.state.posts) {
    console.log('hello')
    // console.log(`${property}: ${this.state.posts[property]}`);
  }
}

  render() {
    return <div>
      <div style={{ display: 'flex', justifyContent: 'center' }}>
        <span> hey, i am left text </span>
        <button onClick={this.Club}> Click Club </button>
      </div>
    </div>;
  }
}

export default App;
John V
  • 7
  • 2
  • 5
  • 1
    You need to bind `this` to event handlers or just use arrow functions to fix the problem. Read more about `this` binding here - https://www.freecodecamp.org/news/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb/ – Dhilip H Oct 04 '21 at 04:41
  • yes, How could i forget this. Thanks Dhilip. – John V Oct 04 '21 at 04:48
  • Refer to this https://stackoverflow.com/questions/45998744/react-this-state-is-undefined, you need to bind all your event handling functions to `this`. So in your case, `onClick={this.Club.bind(this)}` fixes the issue. – Roshan Kanwar Oct 04 '21 at 04:49

1 Answers1

1
import React from "react";
import "./styles.css";

class App extends React.Component {
  state = {
    posts: {
      name: "naveen",
      mail: "naveen9@gmail.com"
    }
  };
  club() {
    if (this.state.posts) {
      for (const property in this.state.posts) {
        console.log(property);
      }
    }
  }
  render() {
    return (
      <div>
        <button onClick={() => this.club()}>click</button>
      </div>
    );
  }
}
export default App;

You can use a conditional class.and it is working for me you can check here https://codesandbox.io/embed/cool-cerf-fxh9u?fontsize=14&hidenavigation=1&theme=dark

Naveenkumar M
  • 616
  • 3
  • 17