I have a problem with autoFocus. It doesn't work for me, but using it:
<input onChange={this.handleName} value={this.state.name} placeholder="Name..." type="text" autoFocus />
If you render your React component into a detached element, React will call focus() too soon. This will result in the input not focusing when your React tree gets added to the DOM.
Autofocusing using React useRef() and useEffect() Hooks We can also get the same functionality with the useRef() and useEffect() React Hooks. Here is the same form using these Hooks: import React, { useRef, useEffect } from "react"; const Form = () => { const emailInput = useRef(null); useEffect(() => { if (emailInput.
Autofocus can create confusion, especially for screenreader users, by moving them to a form field without permission or context. When the page <input> includes other content, or when the input field isn't the primary purpose of the page, it's best practice to let visitors choose to fill out a form.
To access this, we need to use a current keyword like inputRef. current, and as we have to tell React to focus on this, we can just use focus() method inside the useEffect Hook. Every time you refresh the page or open it in a new tab, you will notice that the input field will always be focused.
<input type="text" autoFocus .../>
<input type="text" autoFocus={true} .../>
<input type="text" autoFocus="true" .../>
<input type="text" autoFocus="autofocus" .../>
…even though in each case, the web inspector showed that <input type="text" autofocus .../>
was rendered 🤔
Perhaps it's because of this phenomenon, I'm not sure:
If you render your React component into a detached element, React will call
focus()
too soon. This will result in theinput
not focusing when your React tree gets added to the DOM.
import React, { useRef, useEffect } from "react";
export default function SignIn() {
const inputElement = useRef(null);
useEffect(() => {
if (inputElement.current) {
inputElement.current.focus();
}
}, []);
return (
<div>
<form action="...">
<input
ref={inputElement} // yes, this is working in Chrome on Mac
type="text" // allows username also; type 'email' woud insist on '@' sign
name="email"
placeholder="Email address"
autoComplete="email"
required
...
/>
</form>
</div>
);
}
That's strategy #2 from Daniel Johnson
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With