I am trying to focus Parent input box after a Dialog box is popped up. I tried passing Parent’s ref to child and focus from child but hard time making it to work.
I’d appreciate your help.
Code sandbox: https://codesandbox.io/s/modal-components-react-custom-hooks-forked-iyumhx?file=/src/Modal.js
Code:
const App = () => {
const { isShowing, toggle, setIsShowing } = useModal();
const [input, setInput] = useState("");
const ref = useRef();
useEffect(() => {
if (input != "") setIsShowing(true);
}, [input]);
return (
<div className="App">
<input type="text" ref={ref} onChange={(e) => setInput(e.target.value)} />
<Modal
isShowing={isShowing}
hide={toggle}
forwardRef={ref}
input={input}
/>
</div>
);
};
here on Console.log ref, I can see the Ref is defined but the focus
function does not work.
const Modal = ({ isShowing, hide, forwardRef, input }) => {
useEffect(() => {
console.log(forwardRef);
forwardRef.current.focus();
}, []);
return (
<>
<M
isOpen={isShowing}
role="dialog"
autoFocus={true}
centered={true}
size="lg"
// query={query}
scrollable={false}
>
From Parent {input}
</M>
</>
);
};
3
Answers
Change your modal useEffect to
Put autofocus false on the modal. This will prevent the modal from stealing focus from the input.
The issue is that the modal from reactstrap library has
autoFocus={true}
by default, you have to set it to false, you also don’t need help from useRef. here is working code:App.jsx
Modal.jsx
useBoolean.js