Skip to content

Instantly share code, notes, and snippets.

@qasimmehdi
Last active December 15, 2020 08:30
Show Gist options
  • Save qasimmehdi/61f8a15d89d40bde4658e1e04e831fc5 to your computer and use it in GitHub Desktop.
Save qasimmehdi/61f8a15d89d40bde4658e1e04e831fc5 to your computer and use it in GitHub Desktop.
React custom input with react-bootstrap
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