Junior — Senior
Detect and fix errors in a React component
livecode
Task condition
In the React component below, there are logical errors that prevent the input field from receiving focus when displayed. Find and fix them by changing the code so that the button shows the input and immediately focuses on it.
import { useRef, useState } from "react";
export default function App() {
const [visible, setVisible] = useState(false);
const refInput = useRef();
const handleToggle = () => {
setVisible(true);
refInput.current.focus();
};
return (
<div>
<button onClick={handleToggle}>Show and focus input</button>
{visible && <input ref={refInput} type="text" />}
</div>
);
}