Skip to content

Cannot read property ‘length’ of undefined – after pressing ‘Enter’ key the value become undefined

Why when I’m pressing the Enter key the value of idNumber becomes undefined ?
If I click on the button calling checkID() it shows the input‘s string length in the console.log(idNumber)

It’s just so weird

    const [idNumber, setNumber] = useState();

    useEffect(() => {
        const submit = document.getElementById('idNum');
        submit.addEventListener('keyup', enterPressed);
      }, []);

 const onChangeHandler = (event) => {
    const isDigits = event.target.value.replace(/D/g, '');
    setNumber(isDigits);
  };


      const enterPressed = (event) => {
        if (event.key === 'Enter') {
          console.log('idNumber.length ' + idNumber.length);
        
        }
      };

       const checkID = () => {
         console.log(idNumber.length)
         };

       <input 

        value={idNumber}
        id='idNum'
        onChange={(event) => onChangeHandler(event)}
       / >

      <button onClick={checkID}>  </button>

Thanks for everyone.

Answer

You shouldn’t be assigning event handlers manually in React, assign onKeyPress the same way as you assign onChange and it works as expected:

const Comp = () => {

  const [idNumber, setNumber] = useState();

  const onChangeHandler = (event) => {
    const isDigits = event.target.value.replace(/D/g, '');
    setNumber(isDigits);
  };


  const onKeyPress = (event) => {
    if (event.key === 'Enter') {
      console.log(idNumber);

    }
  };

  const checkID = () => {
    console.log(idNumber)
  };
  
  return (
    <div>
      <input 

        value={idNumber}
        id='idNum'
        onChange={(event) => onChangeHandler(event)}
        onKeyPress={(event) => onKeyPress(event)}
       / >

      <button onClick={checkID}>Btn</button>
    </div>
  )
}

ReactDOM.render(<Comp />, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>
<script>
  var {
    useReducer,
    useEffect,
    useState,
    useRef,
    useCallback
  } = React
</script>
<div id="root"></div>