I have a webpage where users have a list of images they’ve uploaded. They have three buttons: Upload Image/Download Image/Delete Image. When the user clicks Delete, the Upload button will hide and Download Image/Delete Image turn to Delete/Cancel respectively.
When the user clicks this new Delete button, a modal will show up to confirm the users choice (yes/no). Whether or not the user hits Yes or No, I need to manually set focus on a button that would return a Keyboard user’s focus to where it was before the Modal opened (i.e. the Cancel button if they hit no). These button swaps are handled with conditional rendering statements. A rough outline of my code is as follows:
export const Images = ({ setUserImages, userImages }) => {
const cancelRef = useRef(null);
...
const handleFocus = () => {
setShowDeleteModal(false);
cancelRef.current.focus();
};
return (
<Container>
...
<ButtonsContainer>
{enableSelect ? (
<>
{selectionType === "delete" && (
<>
{" "}
<Button onClick={() => setShowDeleteModal(true)}>Delete</Button>
<Button
ref={cancelRef}
onClick={() => {
setEnableSelect(false);
setSelectedImages([]);
}}
>
Cancel
</Button>
</>
)}
{selectionType === "download" && (
<>
{" "}
<Button
onClick={() => handleDownload()}
>
Download
</Button>
<Button
onClick={() => {
setEnableSelect(false);
setSelectedImages([]);
}}
>
Cancel
</Button>
</>
)}
</>
) : (
/* show upload/download/delete instead */
)}
</ButtonsContainer>
<ImagesContainer>{renderedImages()}</ImagesContainer>
{showDeleteModal && (
<Modal
onClose={() => {
setShowDeleteModal(false);
setSelectedImages([]);
}}
>
<ModalInner>
<h2>Are you sure you want to delete the selected image(s)?</h2>
<ButtonWrapper>
<Button primary onClick={() => handleDelete()}>
Yes
</Button>
<Button secondary onClick={handleFocus}>
No
</Button>
</ButtonWrapper>
</ModalInner>
</Modal>
)}
</Container>
)
Before adding refs, when a keyboard user exited the modal, the focus would throw them all the way to the bottom of the page into the footer, which is outside of the body of the page. This only occurs on chromium browsers, doesn’t happen on Firefox, which is why I’m in this mess.
For some reason the ref is always null when I try this, despite the Cancel button being rendered on screen. I haven’t used refs much, so I’m a bit uneducated, but could the issue be that the Cancel button is being rendered conditionally?
I also tried using autoFocus with some state stuff but it didn’t do anything.
Sorry about the code formatting. I had to cut out a bunch of irrelevant content and it got a bit messy.



