Search code examples
reactjsantd

Auto focus on modal open


How to focus to input after modal has been opened? I can't use useRef cause it's not a component and autoFocus is not working, probably cause I have to click button to open this modal

export const payModal = () => {
    confirm({
        icon: " ",
        title: <Input type="text" />,
    })
}

Solution

  • Add an id and access the input by querySelector and focus

    export const payModal = () => {
        confirm({
            icon: " ",
            title: <Input id="focus-input" type="text" />,
        })
    }
    const openModalFn = () => {
        payModal();
        setTimeout(() => {
            document.querySelector('#focus-input')?.focus()
        }, 100); // if there's a transition and the input is not available, increase the number to the transition duration
    }