I have the following Modal
component. Upon a button click, I open the modal.
I can then close Modal with a close button. When the modal closes, I wan to focus
on another div element.
This works fine as long as I tab to the close button and press enter or space or left mouse click.
But if I don’t tab to close button. And instead only mouse click to close modal, the focus does not land on the div.
Is this expected behaviour? I am trying to land focus on the div even when mouse clicked without tabbing.
This is the modal.
import React, { useState } from 'react';
function Modal(props) {
const [isOpen, setIsOpen] = useState(false);
const btnRef = props.btnRef;
const openModal = () => {
setIsOpen(true);
};
const closeModal = () => {
setIsOpen(false);
btnRef.current.focus(); // the focus logic
};
const handleModalClick = (e) => {
if (e.target === e.currentTarget) {
closeModal();
}
};
return (
<>
<button id='open-btn' onClick={openModal}>Open Modal</button>
{isOpen && (
<div
style={{ backgroundColor: "greenyellow", padding: 10, margin: 10 }}
className="modal" onClick={handleModalClick}>
<div className="modal-content">
<h2>{props.title}</h2>
<p>{props.content}</p>
<button id='close-btn' onClick={closeModal}>Close Modal</button>
</div>
</div>
)}
</>
);
}
export default Modal;
This is how I am calling the Modal.
Also where the div on which I wish to focus on is located.
import {useRef} from 'react'
import './App.css'
import Modal from "./Modal.jsx";
const App = () => {
const btnRef = useRef(null);
return (
<div className="App">
<div>
<div id='modal'>
<Modal
title="Example Modal"
content="This is some example content for the modal."
btnRef={btnRef}
/>
</div>
{/* This is the div where the focus should land after modal closes */}
<div
id='focus-div'
ref={btnRef}
tabIndex='0'
onClick={() => alert('something')}
style={{ padding: 20, backgroundColor: "yellow", cursor: 'pointer' }}
>
{'name'}
</div>
</div>
</div>
)
};
export default App