0

please help. in my code something wrong, but i cant understand what exactly, probably syntax mistake, but i cant find here:

import React, { Component } from 'react';

class Note extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editing: false
    }
  }
  edit() {
    **this.setState({ editing: true })** // probaly problem here
  }
  save() {
    this.setState({ editing: false }) // here
  }
  remove() {
    alert("Removing Note") //and here
  }
  renderForm() {
    return (
      <div className="note">
        <textarea></textarea>
        <button onClick={ this.save }></button>
      </div>
    )
  }
  renderDisplay() {
    return (
      <div className="note">
        <p>{ this.props.children }</p>
        <span>
          <button onClick={ this.edit }>EDIT</button>
          <button onClick={ this.remove }>X</button>
        </span>
      </div>
    )
  }
  render() {
    if( this.state.editing ) {
      return this.renderForm()
    } else {
      return this.renderDisplay()
    }
  }
}

export default Note;

message from chrome is: "Cannot read property 'setState' of null" on line bold this.setState({ editing: true }), after i click on button "edit",

John Smith
  • 69
  • 11

1 Answers1

0

Your methods need to be bound to the class.

constructor(props) {
  super(props);
  this.state = {
    editing: false
  }
  this.edit = this.edit.bind(this);
  this.save = this.save.bind(this);
}

There's also an experimental/proposal feature that enables you to have these bound without explicitly binding by using arrow functions as class methods. This question has more info.

Community
  • 1
  • 1
Andy_D
  • 4,112
  • 27
  • 19