Set state with this.setState question

Hello all :slight_smile:

I’ll get straight into it, I’m having issues executing the following code on VS CODE

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'Initial State'
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    // Change code below this line
    return this.setState({
      name: 'React Rocks!'
    });
    // Change code above this line
  }
  render() {
    return (
      <div>
        <button onClick={this.handleClick}>Click Me</button>
        <h1>{this.state.name}</h1>
      </div>
    );
  }
};

This is from the set state challenge in the front end development libraries section.

This is my code on VS CODE

// set state with this.setState

class MyComponent2 extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
      name:'Initial State'
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    return this.setState({
      name: 'Final State'
    });
  }

  componentDidMount() {
    this.handleClick
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>Click Me</button>
        <h1>{this.state.name}</h1>
      </div>
    );
  }
};

let cont1 = new MyComponent2();

JSX = cont1.render() // important to remember if you want to directly refer

ReactDOM.render(
  <div id="challenge-node">

  </div>, document.getElementById('root')
)

ReactDOM.render(
  JSX,
  document.getElementById('challenge-node')
);

For some reason, my browser doesn’t update when I click the button. I’ve looked at documentation online and searched around for a solution, but so far most people seem to be talking about lifecycle methods, which I haven’t touched upon yet.

Does anyone know why the above code works in the FCC environment but not on VS CODE? I’ve already installed the react npm so I wouldn’t think it would be an issue there

Tjhanks

Figured it out!

In the end it was because I was assigning my class to a JSX element and then rendering it in advance before running it through ReactDOM

Though I still don’t fully understand the mechanisms behind this, it was preventing my states from being updated dynamically.

Just in case anyone else stumbles upon this issue also!

If there are any other more experienced members who understand this more in depth, I would be grateful for your guidance :slight_smile:

Cheers,

Don

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.