Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS onChange prevent user keep typing

Tags:

reactjs

Is there a way where you can stop user typing when the words limits exceeds.

At the moment i have onChange in a textarea and e.preventDefault();. However it doesn't seems to stop users from typing. is there anyway can achieve this, i know you can addEventlister for keypress and prevent the default. but how does reactJS achieve the same functionality?

In jQuery: (how do i achieve the same in reactJS)?

  $(function(){
    $('textarea').keypress(function() {
      var l = $(this).val().split(' ');
      if(l.length > 50){
        return false;
      }
    })
  })
like image 572
Bill Avatar asked Oct 29 '15 06:10

Bill


People also ask

How do you execute a function only after the user stops typing React?

Solution. To avoid that problem, we better execute a function in proper timing which means after a user stops typing for a while. And setTimeout helps us to do that. The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

How do I stop onChange event in React?

For a simpler solution, you can do e. preventDefault on onMouseDown event to prevent onChange from firing.


2 Answers

In react you can use onKeyPress event and use .preventDefault, .stopPropagation methods, like this

var Component = React.createClass({
    handleKeyPress: function(e) {
        var value = e.currentTarget.value.split(' ');

        if (value.length > 10) {
            e.preventDefault();
            e.stopPropagation();
        } else {
            console.log(value);
        }
    },
    render: function() {
        return <textarea onKeyPress={ this.handleKeyPress }></textarea>;
    }
});

Example

return false from within a jQuery event handler is effectively the same as calling both e.preventDefault and e.stopPropagation

like image 150
Oleksandr T. Avatar answered Oct 05 '22 07:10

Oleksandr T.


What about <textarea maxLength={10}/> ?

http://www.w3schools.com/tags/att_input_maxlength.asp

like image 27
ersefuril Avatar answered Oct 05 '22 06:10

ersefuril