Created
February 1, 2021 19:27
-
-
Save dayhaysoos/d949e38984fc327dca15b8022c380aca to your computer and use it in GitHub Desktop.
This file contains hidden or 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, { useState } from "react"; | |
// ui programming | |
// | |
// gif: https://share.getcloudapp.com/BluYJZjy | |
function Challenge() { | |
const [numberInput, setNumberInput] = useState(""); | |
function formatString(e) { | |
const input = e.target.value; | |
let newStr = ""; | |
// Input would only be this state if there were no values, might as well reset to empty string | |
if (input === "(") { | |
setNumberInput(""); | |
} | |
for (let i = 0; i < input.length; i++) { | |
// only run this logic if the current input is a number | |
if (!isNaN(parseInt(input[i]))) { | |
newStr = newStr + input[i]; | |
// add ( if the length is 1 | |
if (newStr.length === 1) { | |
newStr = `(${newStr}`; | |
} | |
// add ) at the point of the new string's 4th index and only if there's another input after | |
if (newStr.length === 4 && input[i + 1]) { | |
newStr = newStr + ")"; | |
} | |
// add ) at the point of the new string's 9th index and only if there's another input after | |
if (newStr.length === 9 && input[i + 1]) { | |
newStr = `${newStr}-`; | |
} | |
} | |
} | |
setNumberInput(newStr); | |
} | |
return ( | |
<div> | |
<input | |
value={numberInput} | |
onChange={formatString} | |
placeholder="(555) 555-5555" | |
maxLength="14" | |
/> | |
</div> | |
); | |
} | |
export default Challenge; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment