Last active
December 15, 2020 08:30
-
-
Save qasimmehdi/61f8a15d89d40bde4658e1e04e831fc5 to your computer and use it in GitHub Desktop.
React custom input with react-bootstrap
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, { useState } from "react"; | |
export default function CustomInput(props) { | |
const { error, inputProps, regex, className, onInput } = props; | |
const [showError, setShowError] = useState(false); | |
const [text, setText] = useState(""); | |
const handleChange = (val) => { | |
setText(val); | |
if (regex.test(val)) { | |
setShowError(false); | |
} else { | |
setShowError(true); | |
} | |
onInput && onInput(val); | |
}; | |
return ( | |
<div className={className}> | |
<input | |
value={text} | |
className={showError ? "form-control border-danger" : "form-control"} | |
{...inputProps} | |
onChange={(e) => handleChange(e.target.value)} | |
/> | |
{showError && error ? ( | |
<small className="text-danger">{error}</small> | |
) : null} | |
</div> | |
); | |
} | |
<CustomInput | |
className="form-group col-md-3" | |
inputProps={{ placeholder: "test", maxLength: "50" }} | |
error="Required" | |
regex={regexes.url} | |
onInput={(val) => console.log(val)} | |
/> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment