Make inputs controlled

This commit is contained in:
Justin Edmund 2022-12-23 20:00:09 -08:00
parent 05c8cf2c38
commit feba0271a8

View file

@ -1,5 +1,6 @@
import React, { useEffect, useState } from 'react'
import classNames from 'classnames'
import React from 'react'
import './index.scss'
interface Props
@ -15,8 +16,22 @@ const Input = React.forwardRef<HTMLInputElement, Props>(function input(
props: Props,
forwardedRef
) {
// States
const [inputValue, setInputValue] = useState('')
// Classes
const classes = classNames({ Input: true }, props.className)
const { value, ...inputProps } = props
const { defaultValue, ...inputProps } = props
// Change value when prop updates
useEffect(() => {
setInputValue(`${props.value}`)
}, [props.value])
function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
setInputValue(event.target.value)
if (props.onChange) props.onChange(event)
}
return (
<label className="Label" htmlFor={props.name}>
@ -24,8 +39,9 @@ const Input = React.forwardRef<HTMLInputElement, Props>(function input(
{...inputProps}
autoComplete="off"
className={classes}
defaultValue={props.value || ''}
value={inputValue}
ref={forwardedRef}
onChange={handleChange}
formNoValidate
/>
{props.label}