Sydney Loteria
Sydney Loteria

Reputation: 10451

Prevent textfield newline when enter - reactjs

I would like to ask how can I prevent the cursor in going to the next line when I empty the state value of my textfield after I press enter. So far what I have is when you press enter it clears the value of the textfield but the cursor is going to the next line. Here's what I've got:

import React, { Component } from 'react';
import Textfield from 'react-mdl/lib/Textfield';
import "./style.css";

class ChatMessageBox extends Component {
    constructor(props){
        super(props);
        this.state = {
            messageBox: ''
        };
    }
    handleMessageBox(event){
        if(event.key === "Enter"){
            this.setState({
                messageBox: ''
            });

        }
    }
    handleMessageBoxOnChange(event){
        this.setState({
            messageBox: event.target.value
        });
    }
    render(){
        return (
            <div className="chat-message-box">
                <Textfield
                    onKeyPress={(e) => { this.handleMessageBox(e) }}
                    onChange={ (e) => { this.handleMessageBoxOnChange(e) }}
                    value={this.state.messageBox}
                    label="Type a message"
                    rows={4}
                />
            </div>
        );
    }
}

export default ChatMessageBox;

Upvotes: 1

Views: 3652

Answers (2)

Tzook Bar Noy
Tzook Bar Noy

Reputation: 11677

I think those 2 events that you have run on after the other, you will probably need to use only one of them or try to handle that properly.

 onKeyPress={(e) => { this.handleMessageBox(e) }}

 onChange={ (e) => { this.handleMessageBoxOnChange(e) }}

both events run when you click "enter", try to check that with console logs to see what is going on there and how the state changes.

Upvotes: 0

Tharaka Wijebandara
Tharaka Wijebandara

Reputation: 8065

Adding a new line to the text when "Enter" key is pressed, is the default behavior of a text field. You have to explicitly prevent that if you want to override that behavior. You can do that with event.preventDefault().

handleMessageBox(event) {
  if (event.key === "Enter") {
    event.preventDefault();
    this.setState({
      messageBox: ""
    });
  }
}

Upvotes: 7

Related Questions