I want my input to be locked to focus. I tried this
onBlur={this.click()}
but it didn't work. How do I do it?
CodePudding user response:
give it an autoFocus (camelCase because its react/jsx) attribute
<input type="text" autoFocus/>
if thats what you mean.
CodePudding user response:
The autoFocus attribute is a boolean attribute.
When present, it specifies that an element should automatically get focus when the page loads.
Try this
CodePudding user response:
Use event.target.focus instead of click. You might also want to [invoke this at the end of the event loop][1], i.e. after a timeout of 0ms:
const onBlur = (e) => {
window.setTimeout(() => e.target.focus(), 0);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<input type="text" onBlur={onBlur} />
</div>
);
See proof-of-concept example:
CodePudding user response:
You can attach a ref to the input and set it to focus when the onBlur event is fired
import * as React from "react";
export default function App() {
const inputRef = React.useRef();
const handleOnblur = () => {
inputRef.current.focus();
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<input ref={inputRef} onBlur={handleOnblur} placeholder="text1" />
<input placeholder="text2" />
</div>
);
}
