sravan ganji
sravan ganji

Reputation: 5125

How to find out where the error is coming from in ReactJS?

I am getting this error because I am accidentally calling some method in my render method. As my application code is really big I'm unable to find out where is this coming from. enter image description here

When I click on the index.js link in the console it is taking me to the following code. enter image description here

This is what I found after doing some debugging(call stack), But it's not the exact full component code, as there are too many lines of code in the component I'm just posting part of it here. Is there anything wrong with this code:

class Sample extends React.Component {
  constructor(props) {
    super(props);

    this.handleSelect = this.handleSelect.bind(this);

    this.state = {
      activeKey: '',
    };
  }
  handleSelect(activeKey) {
    this.setState({ activeKey });
  }

  render() {
    if (this.state.activeKey === '') {
      activeKey = this.getDefaultKey();
      this.handleSelect(activeKey);
    }
    return (
      <PanelGroup
        accordion
        activeKey={this.state.activeKey}
        onSelect={this.handleSelect}
      >
        {optionList}
      </PanelGroup>
    );
  }
}

Upvotes: 6

Views: 11000

Answers (2)

Steve Archer
Steve Archer

Reputation: 641

You're calling this.handleSelect in the render function, which calls setState. As the error says, you can't do this. Can't say for sure without seeing the whole component and knowing what it's supposed to do, but my best guess at something that would at least not error:

class SampleOptions extends React.Component {
  constructor(props, context) {
     super(props, context);

    this.handleSelect = this.handleSelect.bind(this);

    this.state = {
      activeKey: this.getDefaultKey(),
    };
  }
  handleSelect(activeKey) {
    this.setState({ activeKey });
  }

  render() {
    return (
      <PanelGroup
        accordion
        activeKey={this.state.activeKey}
        onSelect={this.handleSelect}
      >
        {optionList}
      </PanelGroup>
    );
  }
}

Upvotes: 1

Conrad Kay
Conrad Kay

Reputation: 140

I would first use the react dev tools chrome extension first, you could also install the redux dev tools if you are using redux, both of these can find errors in state or props.

Most likely, though, there is an error in one of your components, and you should update your question with either snippets or a link to the codebase.

Upvotes: 3

Related Questions