labyrinth-frontend/src/ValidatingInputNumberField.js
Manuel Friedli ae5a58acf8 Enable use of <>-fragment (update dependencies).
Update style of solution-AND-usermarked fields.
2023-04-16 02:35:34 +02:00

41 lines
1.6 KiB
JavaScript

import React, {useState} from 'react';
export default function ValidatingInputNumberField({
id,
label,
value = 0,
constraints = {},
validatorFn = (value) => {
return {valid: true, value};
},
disabled = false,
onChange = _ => {
}
}) {
const [error, setError] = useState(null);
const handleValueChange = (e) => {
const value = e.target.value;
const validation = validatorFn(value);
if (!validation.valid) {
setError(validation.message);
} else {
setError(null);
}
onChange(validation.value);
};
return (
<>
<label htmlFor={id}>{label}: </label>
<input id={id}
type={"number"}
onChange={handleValueChange}
value={value || ""}
min={constraints.min || null}
max={constraints.max || null}
disabled={disabled}
/>
{!!error && <span>{error}</span>}
</>
);
}