Input
Input is a lower-level constructs upon which all Grapes inputs are built.
View source codeBuild a number input
const Demo = () => {
const [value, setValue] = useState(0);
return (
<FormField label="Quantity">
<Input
placeholder="Enter a quantity"
type="number"
value={value}
onChange={(event) => {
setValue(event.target.valueAsNumber);
}}
/>
</FormField>
);
};
Build a email input
You can take advantage of the browser's built-in email validation to verify whether an email address is valid.
const Demo = () => {
const [value, setValue] = useState(0);
const [error, setError] = useState(false);
return (
<FormField label="Email" alertMessage={error ? "Email invalid" : undefined}>
<Input
placeholder="Enter your email"
type="email"
value={value}
onChange={(event) => {
setError(!event.target.checkValidity());
setValue(event.target.value);
}}
/>
</FormField>
);
};
Build a generic input with constraint
You can use the prop min
and max
to defines a minimal and maximal value for your input and then leverage the validation constraint API to verify if the input meets the defined constraints.
const Demo = () => {
const [value, setValue] = useState(0);
return (
<FormField label="Quantity">
<Input
placeholder="Enter a quantity"
type="number"
min={3}
max={5}
value={value}
onChange={(event) => {
if (event.target.checkValidity()) {
setValue(Number.isNaN(event.target.valueAsNumber) ? "" : event.target.valueAsNumber);
}
}}
/>
</FormField>
);
};
You can also use the prop pattern
for text input:
const Demo = () => {
const [value, setValue] = useState("");
return (
<FormField label="Name">
<Input
placeholder="Enter a name"
type="text"
// Only lowercase letters, with a maximum length of 8 characters.
pattern="[a-w]{0,8}"
value={value}
onChange={(event) => {
if (event.target.checkValidity()) {
setValue(event.target.value);
}
}}
/>
</FormField>
);
};