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 classNames from 'classnames'
|
||||||
import React from 'react'
|
|
||||||
import './index.scss'
|
import './index.scss'
|
||||||
|
|
||||||
interface Props
|
interface Props
|
||||||
|
|
@ -15,8 +16,22 @@ const Input = React.forwardRef<HTMLInputElement, Props>(function input(
|
||||||
props: Props,
|
props: Props,
|
||||||
forwardedRef
|
forwardedRef
|
||||||
) {
|
) {
|
||||||
|
// States
|
||||||
|
const [inputValue, setInputValue] = useState('')
|
||||||
|
|
||||||
|
// Classes
|
||||||
const classes = classNames({ Input: true }, props.className)
|
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 (
|
return (
|
||||||
<label className="Label" htmlFor={props.name}>
|
<label className="Label" htmlFor={props.name}>
|
||||||
|
|
@ -24,8 +39,9 @@ const Input = React.forwardRef<HTMLInputElement, Props>(function input(
|
||||||
{...inputProps}
|
{...inputProps}
|
||||||
autoComplete="off"
|
autoComplete="off"
|
||||||
className={classes}
|
className={classes}
|
||||||
defaultValue={props.value || ''}
|
value={inputValue}
|
||||||
ref={forwardedRef}
|
ref={forwardedRef}
|
||||||
|
onChange={handleChange}
|
||||||
formNoValidate
|
formNoValidate
|
||||||
/>
|
/>
|
||||||
{props.label}
|
{props.label}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue