David
David

Reputation: 7456

Textarea: How do I allow newline on ALT + ENTER pressed?

I'm using React and have a Textarea. I've bound an action to Enter such that it no longer creates a newline. Using SHIFT + ENTER is also not an option. When I try to use ALT + ENTER, it doesn't work. This could also be demonstrated by Stack Overflow textareas. Is there a way to maybe programmatically trigger an Enter press when I detect ALT + ENTER?

Upvotes: 1

Views: 7592

Answers (2)

Abolfazl Miadian
Abolfazl Miadian

Reputation: 3159

this is my way, and I think it is awesome, I like it, enjoy!

import React, { Component } from 'react';

export default class myComp extends Component {

    constructor(props) {
        super(props);
        let state = {msg_text:""};
        this.state                      =   state;
        this.handleChange               =   this.handleChange.bind(this);
        this.addNewLineToTextArea       =   this.addNewLineToTextArea.bind(this);
    }  

    onKeyPress = (e) => {
        if (e.keyCode === 13 && e.shiftKey) {
            e.preventDefault();
            this.addNewLineToTextArea();
        }
    };  


    addNewLineToTextArea(){
        let msg_text = this.state.msg_text+"\r\n";
        this.setState({msg_text: msg_text});
    }


    handleChange(funcArg) {
        let new_state = {};
        new_state[funcArg.name] = funcArg.event.target.value;
        this.setState(new_state);
        funcArg.event.target.setCustomValidity("");
    }

  render() {
        return (
             <div>
                  <textarea rows="3" placeholder="write..." onChange={(e) => 
                       this.handleChange({"event":e,"name":"msg_text"})} onKeyDown={this.onKeyPress} 
                       value={this.state.msg_text || ''}  >
                  </textarea> 
             </div>
            )}
        }

Upvotes: 0

ZeroZipZilch
ZeroZipZilch

Reputation: 721

Assuming it's a regular HTML textarea, using JavaScript you could use the following snippet to programmatically add a new line

var textarea = document.querySelector('#textarea');
textarea.value = textarea.value + "\r\n";

A full example of the event could look like this

document.addEventListener('keydown', function(event) {
    if(event.altKey) {
       this.setState({
           altKey: true
       });
    }

    if((event.keyCode == 13 || event.which == 13) && this.state.altKey) {
        var textarea = document.querySelector('#textarea');
        textarea.value = textarea.value + "\r\n";
    }
});

document.addEventListener('keyup', function() {
       this.setState({
           altKey: false
       });
}

Here you would define altKey as false in your state when your component loads and add the eventListener inside of componentDidMount().

Upvotes: 4

Related Questions