skip to Main Content

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


  1. its fine to use useState for input
    also the if (onChange) onChange(e.target.value) can be replaced by onChange?.(e.target.value)

    Login or Signup to reply.
  2. It is good to use controlled component, instead of uncontrolled component.
    You can code like this.

    const [value, setValue] = useState("");
    
    ...
    
    <form>
        <button disabled={value === ""}>BUTTON</button>
        <input value={value} onChange={e=>setValue(e.target.value)}></input>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search