Skip to content

Instantly share code, notes, and snippets.

@dayhaysoos
Created February 1, 2021 19:27
Show Gist options
  • Save dayhaysoos/d949e38984fc327dca15b8022c380aca to your computer and use it in GitHub Desktop.
Save dayhaysoos/d949e38984fc327dca15b8022c380aca to your computer and use it in GitHub Desktop.
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