Sobes.tech
Back to tasks
Junior — Senior
30

Отображение инпута с автоматическим фокусом по нажатию кнопки

Companies where asked:

Сибинтэк
Get help with live coding in real time with Sobes Copilot
Task condition

Требуется, чтобы после клика на кнопку сразу появлялось текстовое поле и получало фокус. Проверьте, корректно ли реализовано данное поведение, и при необходимости внесите поправки.

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;