Junior — Senior
Display input with automatic focus on button press
livecode
Task condition
It is required that after clicking the button, a text input field immediately appears and receives focus. Check whether this behavior is implemented correctly, and make adjustments if necessary.
import React, { useState, useRef } from 'react';
const ToggleComponent = () => {
const [showInput, setShowInput] = useState(false);
const inputElementRef = useRef(null);
const toggleVisibility = () => {
setShowInput(prev => !prev);
if (inputElementRef.current) {
inputElementRef.current.focus();
}
};
return (
<>
<button onClick={toggleVisibility}>Toggle Input</button>
{showInput && <input ref={inputElementRef} />}
</>
);
};
export default ToggleComponent;