In React, i have a form with a input and a button. I use a useRef to controll the actual value of input. I want a button be disable when input text is empty, but when a use a useRef i can’t trigger a re-render. Is good practice use useState() to controll input state? Has another soluton to this case?
<TitleInputText
name=''
type='text'
title={inputTitle}
placeholder={inputPlaceholder}
onChange={(value) => (graphicName.current = value)}
/>`
`export const TitleInputText: FC<TitleInputTextProps> = ({
title,
type,
name,
placeholder,
onChange,
}) => {
return (
<S.Container data-testid='title-input'>
<Title label={title} size='small' />
<S.InputTitleAnalytic
type={type}
name={name}
placeholder={placeholder}
onChange={(e) => {
if (onChange) onChange(e.target.value)
}}
/>
</S.Container>
)
}
12345678910123432112312
2
Answers
its fine to use
useState
for inputalso the
if (onChange) onChange(e.target.value)
can be replaced byonChange?.(e.target.value)
It is good to use controlled component, instead of uncontrolled component.
You can code like this.