Search code examples
javascriptreactjssanitization

JS Array.prototype.split() ignores the first character


I am currently working on a manual sanitization, that formates/fixes dates written in this format 02101998 to 02/10/1998 (for example). To achieve this, I want to chop any written input in smaller parts (0210=> [[0],[2],[1],[0]]) My method below ignores always the first written char.

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [state, setState] = useState("");

  const handleInput = (e) => {
    setState(e.target.value);
    const partChars = e.target.value.split('');
    console.log(partChars);

  };

  return (
    <div className="App">
      <input onKeyPress={handleInput} defaultValue={state} />
    </div>
  );
}

Solution

  • Please try onChange where you used onKeyPress. Actually, it is reading the value of the element when you press a second time.

    ...
      return (
        <div className="App">
          <input onChange={handleInput} defaultValue={state} />
        </div>
      );
    }