I’m following a React tutorial on Youtube and currently have this React code:
import { useRef } from 'react';
const AddItem = ({ newItem, setNewItem, handleSubmit }) => {
const inputRef = useRef();
return (
<form className="addForm" onSubmit={handleSubmit}>
<input
ref={inputRef}
id="addItem"
type="text"
value={newItem}
onChange={(e) => setNewItem(e.target.value)}
/>
<button
type="submit"
onClick={() => inputRef.current.focus()}
// onClick={() => document.getElementById('addItem').focus()} // What does this do differently?
>
</button>
</form>
);
};
export default AddItem;
I’m using useRef()
along with onClick={() => inputRef.current.focus()}
to make sure the text input is focused after clicking the button.
I can do the same thing without the need for the useRef
hook by using onClick={() => document.getElementById('addItem').focus()}
.
Is there a benefit to using the useRef
method over the getElementById
method?