1

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>
  )

}
4
  • Chaging a ref won't trigger another render. Usually it is a bad idea to access methods like focus. What are you trying to acomplish with this code? Please take a look at reactjs.org/docs/refs-and-the-dom.html Commented Nov 19, 2019 at 14:29
  • Still its not clear, why you used useRef, can you give more info? Commented Nov 19, 2019 at 14:29
  • When the component loads I want to clear the form and focus the fullName input Commented Nov 19, 2019 at 14:31
  • what I have now works, but is this the "right way'? Commented Nov 19, 2019 at 14:37

1 Answer 1

3

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/>
Sign up to request clarification or add additional context in comments.

3 Comments

value={email} should this not be value={state.email} ??
I can see that onChange is updating the state, but how does the form get cleared?
I've destructured email and password from state so i don't have to type state.email. Now to clear the form is just setting the state as the initial. state = '' pass = ''

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.