Skip to content

Fix: add type guard to fieldRef.select#12390

Merged
bluebill1049 merged 1 commit intoreact-hook-form:masterfrom
developer-bandi:fix/setFocus
Nov 2, 2024
Merged

Fix: add type guard to fieldRef.select#12390
bluebill1049 merged 1 commit intoreact-hook-form:masterfrom
developer-bandi:fix/setFocus

Conversation

@developer-bandi
Copy link
Copy Markdown
Contributor

@developer-bandi developer-bandi commented Nov 2, 2024

An error occurs if we run setFoucs with {shouldSelect:true} enabled for an element (select) other than input or textArea.
(Because the select element does not have a select method)

Therefore, I added a simple type guard.

const Basic: React.FC = () => {
  const { mode } = useParams();
  const [data, setData] = React.useState({});
  const {
    register,
    handleSubmit,
    setFocus
  } = useForm<{
    selectNumber: string;
  }>({
    mode: mode as keyof ValidationMode,
  });
  
  renderCounter++;


  React.useEffect(() => {
    setFocus("selectNumber",{shouldSelect:true});
  }, [setFocus]);

  return (
    <form
      onSubmit={handleSubmit((data) => {
        setData(data);
      })}
    >
      <select {...register('selectNumber', { required: true })}>
        <option value="">Select</option>
        <option value={'1'}>1</option>
        <option value={'2'}>2</option>
      </select>
      <button id="submit">Submit</button>
    </form>
  );
};

@bluebill1049 bluebill1049 merged commit 143f4a1 into react-hook-form:master Nov 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants