user1933205
user1933205

Reputation: 362

How to handle onKeyUp event in ReactJS form

I have a generic JavaScript function as follows home.js

function numericOdds(e) {
  var valid = /^[1-9]{1}[0-9]{0,1}$/
  var number = /^[1-9]{1}$ | ^[1-9]{1}[0-9]{1}$/
  var lastValid = '';
  var n;
  console.log('Key pressed : ', event.keyCode)
  if (!valid.test(e.target.value)) {
    console.log('target :' + e.target.value);
    n = e.target.value.match(number);
    console.log('n :' + n)
    e.target.value = n ? n : lastValid;
  } else {
    lastValid = e.target.value;
    console.log('lastValid :' + lastValid)
  }
}

It works as expected when I use this in a generic HTML form

<input type="number" name="add-numberOdds" onkeyup="numericOdds(event);" min="1" max="99" required="" id="id_add-numberOdds">

The form fails to load, when I try to use this function in a React Form Component. Here is the React Form Component

<Form.Group>
  <Form.Control type="number" name="add-numberOdds"
    onKeyUp={numericOdds(event)} min="1" max="99"
    required="" id="id_add-numberOdds" />
</Form.Group>

The Console log is as follows:

Key pressed : undefined

The error I am getting is as follows:

Uncaught TypeError: Cannot read property 'match' of undefined
    at numericOdds (home.js:10)

I am getting this error at the time of the form rendering. I think I may be binding this function to the component incorrectly. The function is a generic function and is used elsewhere also. Therefore I don't want to define it inside the component.

Upvotes: 0

Views: 1113

Answers (1)

Christian Fritz
Christian Fritz

Reputation: 21364

You are currently calling the numericOdds function during rendering, as opposed to when the event happens. onKeyUp needs to be a function:

onKeyUp={numericOdds} 

Upvotes: 2

Related Questions