0
votes

I have created a list of input tags wrapped in a div to produce an editable text list.

However, when I add a new element to this list by hitting Enter, the new empty element is automatically populated with the last keyboard input, instead of being blank.

Here is a link the JsBin describing the issue:

https://jsbin.com/kovipurace/edit?html,output

I am expecting an empty input instead.

Is there a way to implement the expected behaviour correctly?

I initially based my code off of the CommentForm in the react tutorial, but I have deliberately not used a form tag to give cleaner use of the hitting the Enter key (don't want to mess around with e.preventDefault() etc.) I have also put in additional functionality in the actual version to allow updating existing values using an onBlur event.

What I have tried:

I have (correctly, hopefully!) implemented controlled components as stated in the docs.

I have experimented with using defaultValue and instead of value but the effect is the same. In both cases I am using {this.props.value}

2
I think there is a misunderstanding here. There is only a single TextEntry element. When React rerenders, it reuses that component. React renders the value of this.state.value. You are not setting the value to an empty string anywhere. If you set it to an empty string, the input will be empty. - Felix Kling
TextEntry sets its initial state from it's props. This is how previous text entries show. I tried explicitly set the value of the lone text element before. I have added that back in to the example. It's value still gets overridden by keyboard input. Please see the updated JsBin - user2232887

2 Answers

0
votes

You create new textentries with textEntry text.

keyHasBeenPressed : function(e) {
    if (e.keyCode == 13) {
      var textEntry = this.refs.textEntry.value;
      this.props.createEntry(textEntry);
    }      
},

All you need is to make the args of createEntry blank.

this.props.createEntry();

https://jsbin.com/daqura/1/edit?html,output

0
votes

I found help on #reactjs IRC channel and commenters here.

In the keyHasBeenPressed function, the state needs to be set explicitly again, as it is in handleChange.

getInitialState is just used to intialize state once in a component's life cycle.