Last active
June 7, 2019 17:15
-
-
Save lwkchan/5bf76f017835313d238a32f4d4afffc7 to your computer and use it in GitHub Desktop.
Ensures that numpad keyboard shows but also shows commas when onBlur- Unfortunately does not work as expected on iOS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import ReactDOM from "react-dom"; | |
import "./styles.css"; | |
const getNumericValueWithCommas = (value) => { | |
const separator = ","; | |
let output = ""; | |
const numbersArray = value | |
.toString() | |
.replace(separator, "") | |
.split(""); | |
let count = 0; | |
for (let i = numbersArray.length - 1; i >= 0; i--) { | |
output += numbersArray[i]; | |
count++; | |
if (count % 3 === 0 && count < numbersArray.length) { | |
output += currencySeparators[locale]; | |
} | |
} | |
output = output | |
.split("") | |
.reverse() | |
.join(""); | |
if (symbol) { | |
return separator + output; | |
} | |
return output; | |
}; | |
export const getNumbersOnly = value => { | |
return value ? value.toString().replace(/[^0-9]/g, "") : ""; | |
}; | |
function App() { | |
const [inputType, setInputType] = React.useState("text"); | |
const [value, setValue] = React.useState(""); | |
const inputEl = React.useRef(null); | |
const isUserFocused = React.useRef(false); | |
return ( | |
<div className="App"> | |
<h1>My input box</h1> | |
<input | |
type={inputType} | |
value={value} | |
ref={inputEl} | |
onChange={e => setValue(e.target.value)} | |
onFocus={() => { | |
if (inputType === "number") { | |
return; | |
} | |
if (!isUserFocused.current) { | |
setValue(getNumbersOnly(value)); | |
} | |
isUserFocused.current = true; | |
setInputType("number"); | |
inputEl.current.focus(); | |
}} | |
onBlur={() => { | |
if (isUserFocused.current) { | |
isUserFocused.current = false; | |
return; | |
} | |
setInputType("text"); | |
setValue(getNumericValueWithCommas(value, "uk")); | |
}} | |
/> | |
</div> | |
); | |
} | |
const rootElement = document.getElementById("root"); | |
ReactDOM.render(<App />, rootElement); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment