Jenny Mok
Jenny Mok

Reputation: 2804

toggle doesn't work in react, no error

My intention is to show the input field when the edit is pressed but with below code it doesn't work, I couldn't find out what is the problem, no error in the console.

http://jsbin.com/yezediloke/1/edit?js,console,output

class TodoItem extends React.Component {
  constructor(){
    super()
    this.isEditing = false;
    this.onClickEdit = this.onClickEdit.bind(this);
  }
  onClickEdit(){
    this.setState({isEditing: !this.isEditing});
  }
  render(){
    return(

      <li>
        <span>{this.props.item}</span>
      {this.isEditing ? '<span><input type="text" /></span>' :''}
      &nbsp;&nbsp;<button onClick={this.onClickEdit}>Edit</button>
      <button>Save</button>
      </li>
    )
  }
}

Upvotes: 0

Views: 562

Answers (1)

A. L
A. L

Reputation: 12639

4 Problems:

1: You didn't set the initial state in constructor:

  constructor(){
    super()
    this.isEditing = false;
    this.onClickEdit = this.onClickEdit.bind(this);
    this.state = { isEditing: false };
  }

2 and 3: Span does not need '' and this.isEditing should be this.state.isEditing

 render(){
    return(

      <li>
        <span>{this.props.item}</span>
/*Look here>>>*/ {this.state.isEditing ? <span><input type="text" /></span> :''}
      &nbsp;&nbsp;<button onClick={this.onClickEdit}>Edit</button>
      <button>Save</button>
      </li>
    )
  }

4: this.isEditing should be this.state.isEditing in onClickEdit

onClickEdit(){
    this.setState({isEditing: !this.state.isEditing});
  }

This works: http://jsbin.com/ganimopalo/1/edit?js,console,output

Upvotes: 2

Related Questions