0

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>
    )
  }
}
2
  • first of all, remove the '' from '<span><input type="text" /></span>' Commented Jan 9, 2017 at 13:08
  • @A.Lau after that? Commented Jan 9, 2017 at 13:10

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

13 Comments

this.isEditing = false is not state?
That is not in the state, that is just in the class. this.state is the state. Hence, this.state.isEditing is where the isEditing you want to be looking at
jsbin.com/cogopuvoke/1/edit?js,console,output can you take a look? doesn't work.
Because you're still using this.isEditing in the render part
A. Lau, why this save handler has error? jsbin.com/cogopuvoke/1/edit?js,console,output
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.