Bill
Bill

Reputation: 5150

React TypeScript: Alternatives to UseRef in functional components

Is there another way of getting/setting the values from the dom that is less expensive than useRef()? Is useRef() to be used lightly as the docs suggest?

import React, { useRef, useEffect } from 'react';

const Join: React.FC = () => {

  const fullName = useRef<HTMLInputElement>(null);
  const email = useRef<HTMLInputElement>(null);
  const password = useRef<HTMLInputElement>(null);
  const myForm = useRef<HTMLFormElement>(null);

  useEffect(() => {
    if (myForm.current) myForm.current.reset();
    if (fullName.current) fullName.current.focus();
  }, []);


  return (
    <div>
      <form ref={myForm}>
       <input type='text' ref={fullName} />
       <input type='text' ref={email} />
       <input type='text' ref={password} />
      </form>
    </div>
  )

}

Upvotes: 1

Views: 4567

Answers (1)

Dupocas
Dupocas

Reputation: 21297

When the component loads I want to clear the form and focus the fullName input

You don't need refs for that

I want to clear the form

  • Make your inputs controlled
  • Declare an empty string as initial value

const Component = () =>{
    const [state, setState] = useState({
        email : '',
        password : ''
    })

    const onChange = ({ target: { value, name } }) =>{
        setState(prev => ({
            ...prev,
            [name] : value
        }))
    } 

    const { email, password } = state
    return(
        <>
            <input value={email} onChange={onChange} id='email'/>
            <input value={password} onChange={onChange} id='password' />
        </>
    )
}

Automatically focus a given input

Just use autofocus for that

<input autofocus/>

Upvotes: 3

Related Questions