Reputation: 477
I have an input element with disable true. Now once i click on a button i want to set the disabled to false and focus on the input element.
I have tried the useRef option as described on react docs and it works if i removed the disabled property but both of them don't work together.
const [edit, setEdit] = useState(false);
const searchInput = useRef(null);
return (
<>
<input
ref={searchInput}
type="text"
name="wnique_name"
id="unique_id"
disabled={!edit}
/>
<button
onClick={() => {
setEdit(true);
searchInput.current.focus();
}}
>
Edit
</button>
</>
);
Upvotes: 1
Views: 5384
Reputation: 1
You can imperatively tell the onClick to make the input disabled false.
<button
onClick={() => {
setEdit(true);
searchInput.current.disabled = false;
searchInput.current.focus();
}}
>
Edit
</button>
</> );
Upvotes: 0
Reputation: 86
The components need to rerender and "enable" the input. Quickfix with setTimeout:
onClick={() => {
setEdit(true);
setTimeout(() => {
searchInput.current.focus();
})
...
Upvotes: 0
Reputation: 12807
You need to add useEffect
to check when the input is enabled.
useEffect(() => {
if (edit) {
searchInput.current.focus();
}
}, [edit]);
return (
<>
<input
ref={searchInput}
type="text"
name="wnique_name"
id="unique_id"
disabled={!edit}
/>
<button
onClick={() => {
setEdit(true);
}}
>
Edit
</button>
</>
);
Upvotes: 3