@instructure/quiz-interactions
Version:
A React UI component Library for quiz interaction types.
52 lines (42 loc) • 1.41 kB
JavaScript
import React, {useState} from 'react'
import PropTypes from 'prop-types'
import {ScientificNumberInput} from '@instructure/quiz-number-input/components/ScientificNumberInput'
function omitProps(props, keysToOmit) {
return Object.fromEntries(Object.entries(props).filter(([key]) => !(key in keysToOmit)))
}
// Wraps ScientificNumberInput, replacing the onChange and onBlur
// props with a single onUpdate handler that only fires on blur.
function VariableInput({onUpdate, value: propValue = undefined, ...restProps}) {
const [value, setValue] = useState(propValue)
const [normalized, setNormalized] = useState(propValue)
const handleBlur = () => {
if (normalized === null) {
setValue(propValue)
setNormalized(propValue)
} else if (normalized != propValue) {
// intentional double-equals
onUpdate(normalized)
}
}
const handleChange = (_event, newValue, newNormalized) => {
setValue(newValue)
setNormalized(newNormalized)
}
return (
<ScientificNumberInput
{...omitProps(restProps, VariableInput.propTypes)}
onBlur={handleBlur}
onChange={handleChange}
showArrows={false}
value={value}
/>
)
}
VariableInput.propTypes = {
onUpdate: PropTypes.func.isRequired,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
}
VariableInput.defaultProps = {
value: void 0,
}
export default VariableInput