rksh rksh - 26 days ago 6
Javascript Question

Clear textarea after enter key

I would like to clear the textarea content after enter key press on react. However when enter key press the text area clears but the enter key remains (new line). How can I fix this?

constructor(){
this.state = { text : '' }
}

keypress(e){
if(e.key == 'Enter'){
this.setState({
send_message: ''
})
}
}

<textarea value={this.state.text} placeholder="Text" rows="1" className="form-textarea typing-area" onKeyPress={this.keypress.bind(this)}></textarea>

Answer

You can use event.preventDefault when the key is 'Enter':

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { text : '' }
    this.handleChange = this.handleChange.bind(this);
    this.keypress = this.keypress.bind(this);
  }
  
  handleChange(event) {
    this.setState({text: event.target.value});
  }
  
  keypress(e){ 
    if(e.key === 'Enter'){
      e.preventDefault();
      this.setState({
        send_message: this.state.text,
        text: '',
      });
    }
  }
  render() {
    return (
      <div>
        <textarea 
          value={this.state.text} 
          placeholder="Text" 
          rows="1" 
          className="form-textarea typing-area" 
          onChange={this.handleChange}
          onKeyPress={this.keypress} 
        />
        <pre>{JSON.stringify(this.state, null, 2)}</pre>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>