Make inputs controlled
This commit is contained in:
parent
05c8cf2c38
commit
feba0271a8
1 changed files with 19 additions and 3 deletions
|
|
@ -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}
|
||||
|
|
|
|||
Loading…
Reference in a new issue