Jason Chen Jason Chen - 4 months ago 37
Javascript Question

Reactjs keypress regex?

Using ReactJS, I am trying to set a keypress regex listener. My code is below.

formation: function() {
var f1c = document.getElementsByClassName('f1t').value;
var validator = new RegExp('^[0-9.]*$');
var runner = validator.test(f1c);
var bling = document.getElementById('f1p2');

if (runner) {
alert("Vegetables");
} else {
alert("Fruits");
}
},


This is called from a separate function, like so.

something: function() {
return (
<input type="text" className="f1t" onKeyUp={this.formation}>something</p>
);
}


The problem is that the keyup event only runs as it should if I remove the if arguments, meaning that the keyup does work. However, there must be something off with my logic.

The code as shown above keeps showing
Fruits
when it is only supposed to show
fruit
if the value of
f1c
is not a number.

Answer

When a user presses a key, and the event fires, the function will get a reference to the element and the key in the form of a React synthetic event.

formation: function(e) {
  var theKeyPressed = e.charCode; // this is normalized for you by React
  var theElementPressed = e.target;
  var theValueOfTheElement = e.target.value;
  // do your thing
},

something: function() {
  return (
    <input type="text" className="f1t" onKeyUp={this.formation}>something</p>
  );
} 

FYI, type="text" is redundant nowadays, it's the default.